My online notes – Section 0005

Note 1: Impersonation for accessing network path

private void ApplyUserCredentials(string Share, string Domain, string Username, string Password)
{
	USE_INFO_2 useInfo = new USE_INFO_2();
	useInfo.ui2_local = string.Empty;
	useInfo.ui2_remote = Share;
	useInfo.ui2_password = Password;
	useInfo.ui2_asg_type = 0;    //disk drive
	useInfo.ui2_usecount = 1;
	useInfo.ui2_username = Username;
	useInfo.ui2_domainname = Domain;
	uint paramErrorIndex;

	uint returnCode = NetUseAdd(null, 2, ref useInfo, out paramErrorIndex);
	if (returnCode != 0)
	{
		throw new Win32Exception((int)returnCode);
	}
}

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern UInt32 NetUseAdd(string UncServerName,UInt32 Level, ref USE_INFO_2 Buf,  out UInt32 ParmError);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct USE_INFO_2
{
	internal string ui2_local;
	internal string ui2_remote;
	internal string ui2_password;
	internal UInt32 ui2_status;
	internal UInt32 ui2_asg_type;
	internal UInt32 ui2_refcount;
	internal UInt32 ui2_usecount;
	internal string ui2_username;
	internal string ui2_domainname;
}

Note 2: Random number generator which does not repeat item.

private static Random rand = new Random ();

public static void Shuffle<T> (IList<T> ilist)
{
    int iIndex;
    T   tTmp;
    for (int i = 1; i < ilist.Count; ++i) {
       iIndex = rand.Next (i + 1);
       tTmp = ilist [i];
       ilist [i] = ilist [iIndex];
       ilist [iIndex] = tTmp;
    }
}

// Und hier noch ein kleines Beispiel für die Verwendung:
List<int> list = new List <int> ();

for (int i = 0; i < 10; ++i) {
   list.Add (i);
}

Shuffle<int> (list);

foreach (int i in list) {
   Console.WriteLine (i);
}

Note 3: ListBox – Automatically scroll CurrentItem into View

<ListBox ItemsSource="{...}" IsSynchronizedWithCurrentItem="True" Extenders:ListBoxExtenders.AutoScrollToCurrentItem="True" />
/// <summary>
/// This class contains a few useful extenders for the ListBox
/// </summary>
public class ListBoxExtenders : DependencyObject
{
  #region Properties

  public static readonly DependencyProperty AutoScrollToCurrentItemProperty = DependencyProperty.RegisterAttached("AutoScrollToCurrentItem", typeof(bool), typeof(ListBoxExtenders), new UIPropertyMetadata(default(bool), OnAutoScrollToCurrentItemChanged));

  /// <summary>
  /// Returns the value of the AutoScrollToCurrentItemProperty
  /// </summary>
  /// <param name="obj">The dependency-object whichs value should be returned</param>
  /// <returns>The value of the given property</returns>
  public static bool GetAutoScrollToCurrentItem(DependencyObject obj)
  {
    return (bool)obj.GetValue(AutoScrollToCurrentItemProperty);
  }

  /// <summary>
  /// Sets the value of the AutoScrollToCurrentItemProperty
  /// </summary>
  /// <param name="obj">The dependency-object whichs value should be set</param>
  /// <param name="value">The value which should be assigned to the AutoScrollToCurrentItemProperty</param>
  public static void SetAutoScrollToCurrentItem(DependencyObject obj, bool value)
  {
    obj.SetValue(AutoScrollToCurrentItemProperty, value);
  }

  #endregion

  #region Events

  /// <summary>
  /// This method will be called when the AutoScrollToCurrentItem
  /// property was changed
  /// </summary>
  /// <param name="s">The sender (the ListBox)</param>
  /// <param name="e">Some additional information</param>
  public static void OnAutoScrollToCurrentItemChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
  {
    var listBox = s as ListBox;
    if (listBox != null)
    {
      var listBoxItems = listBox.Items;
      if (listBoxItems != null)
      {
        var newValue = (bool)e.NewValue;

        var autoScrollToCurrentItemWorker = new EventHandler((s1, e2) => OnAutoScrollToCurrentItem(listBox, listBox.Items.CurrentPosition));

        if (newValue)
          listBoxItems.CurrentChanged += autoScrollToCurrentItemWorker;
        else
          listBoxItems.CurrentChanged -= autoScrollToCurrentItemWorker;
      }
    }
  }

  /// <summary>
  /// This method will be called when the ListBox should
  /// be scrolled to the given index
  /// </summary>
  /// <param name="listBox">The ListBox which should be scrolled</param>
  /// <param name="index">The index of the item to which it should be scrolled</param>
  public static void OnAutoScrollToCurrentItem(ListBox listBox, int index)
  {
    if (listBox != null && listBox.Items != null && listBox.Items.Count > index && index >= 0)
      listBox.ScrollIntoView(listBox.Items[index]);
  }

  #endregion
}


Note 4: How to use Visual C# to obtain the color of the pixel that is referenced by the mouse pointer

using System.Runtime.InteropServices;
private Bitmap myBitmap;
public class Win32APICall
{
	[DllImport("gdi32.dll",EntryPoint="DeleteDC")]
	public static extern IntPtr DeleteDC(IntPtr hdc);

	[DllImport("gdi32.dll",EntryPoint="DeleteObject")]
	public static extern IntPtr DeleteObject(IntPtr hObject);

	[DllImport("gdi32.dll",EntryPoint="BitBlt")]
	public static extern bool BitBlt(IntPtr hdcDest,int nXDest,
		int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,
		int nXSrc,int nYSrc,int dwRop);

	[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")]
	public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, 
		int nWidth, int nHeight);

	[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")]
	public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

	[DllImport ("gdi32.dll",EntryPoint="SelectObject")]
	public static extern IntPtr SelectObject(IntPtr hdc,IntPtr hgdiobjBmp);

	[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
	public static extern IntPtr GetDesktopWindow();

	[DllImport("user32.dll",EntryPoint="GetDC")]
	public static extern IntPtr GetDC(IntPtr hWnd);

	[DllImport("user32.dll",EntryPoint="GetSystemMetrics")]
	public static extern int GetSystemMetrics(int nIndex);

	[DllImport("user32.dll",EntryPoint="ReleaseDC")]
	public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);

	public static Bitmap GetDesktop()
	{
		int screenX;
		int screenY;
		IntPtr hBmp;
		IntPtr  hdcScreen = GetDC(GetDesktopWindow());
		IntPtr hdcCompatible = CreateCompatibleDC(hdcScreen);

		screenX = GetSystemMetrics(0);
		screenY = GetSystemMetrics(1);
		hBmp = CreateCompatibleBitmap(hdcScreen, screenX, screenY);

		if (hBmp!=IntPtr.Zero)
		{
			IntPtr hOldBmp = (IntPtr) SelectObject(hdcCompatible, hBmp);
			BitBlt(hdcCompatible, 0, 0,screenX,screenY, hdcScreen, 0, 0,13369376);
			
			SelectObject(hdcCompatible, hOldBmp);
			DeleteDC(hdcCompatible);
			ReleaseDC(GetDesktopWindow(), hdcScreen);
			
			Bitmap bmp = System.Drawing.Image.FromHbitmap(hBmp); 
			
			DeleteObject(hBmp);
			GC.Collect();
			
			return bmp;
		}
		
		return null;
	}
}
private void label1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
	myBitmap = Win32APICall.GetDesktop();
}
private void label1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
	Color myColor = myBitmap.GetPixel(MousePosition.X,MousePosition.Y);
	label1.BackColor = myColor;
}

Note 5: Linq SelectMany with Conditions

internal class Program
{
	private static void Main(string[] args)
	{
		MetaData metaData1 = new MetaData() { Description = "metaData1" };
		MetaData metaData2 = new MetaData() { Description = "metaData2" };
		MetaData metaData3 = new MetaData() { Description = "metaData3" };
		Level3 level3_1 = new Level3() { Level3Description = "level3_1", Meta = new List<MetaData> { metaData1 } };
		Level3 level3_2 = new Level3() { Level3Description = "level3_2", Meta = new List<MetaData> { metaData1, metaData2 } };
		Level3 level3_3 = new Level3() { Level3Description = "level3_3", Meta = new List<MetaData> { metaData2, metaData3 } };

		Level2 level2_1 = new Level2() { Level2Description = "level2_1", Level2Items = new List<Level3>() { level3_1, level3_2 } };
		Level2 level2_2 = new Level2() { Level2Description = "level2_2", Level2Items = new List<Level3>() { level3_2, level3_3 } };

		Level1 level1_1 = new Level1() { Description = "level1_1", Items = new List<Level2>() { level2_1, level2_2 } };

		var metaDatas = level1_1.Items.Where(lv2 => lv2.Level2Description.Contains("level2_1")).SelectMany(lv2 => lv2.Level2Items)
			.Where(lv3 => lv3.Level3Description.Contains("level3_2")).SelectMany(lv3 => lv3.Meta);

		foreach (MetaData item in metaDatas)
		{
			Console.WriteLine(item.Description);
		}
		Console.ReadLine();
	}
}

internal class Level1
{
	public string Description { get; set; }

	public List<Level2> Items { get; set; }
}

internal class Level2
{
	public string Level2Description { get; set; }

	public List<Level3> Level2Items { get; set; }
}

internal class Level3
{
	public string Level3Description { get; set; }

	public List<MetaData> Meta { get; set; }
}

internal class MetaData
{
	public string Description { get; set; }
}

Note 6: WPF DependencyProperty with type of UIElement

public partial class MyUserControl : UserControl
{
    public static readonly DependencyProperty TestprobProperty =
    DependencyProperty.Register("Testprob", typeof(UIElement),
    typeof(MyUserControl), new PropertyMetadata(TestprobChanged));


    private static void TestprobChanged(DependencyObject aD,
    DependencyPropertyChangedEventArgs aE)
    {
      (aD as MyUserControl).Testprob = (UIElement)aE.NewValue;
    }


    public MyUserControl()
    {
      InitializeComponent();
    }

    public UIElement Testprob
    {
      set
      {
        SetValue(TestprobProperty, value);
      }
      get
      {
        return (UIElement)GetValue(TestprobProperty);
      }
    }
}

and in XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:WpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox x:Name="TextBox1"  />
        <Grid>
        <WpfApplication1:MyUserControl
           Testprob="{Binding ElementName=TextBox1}"/>
    </Grid>
    </StackPanel>
</Window>

Note 7: Open RegistryKey in Windows 64 bit

RegistryKey rk = RegistryKey.OpenBaseKey(
		RegistryHive.LocalMachine,
		RegistryView.Registry64).OpenSubKey(
		@"SOFTWARE\Microsoft\Shared Tools\MSConfig",
		RegistryKeyPermissionCheck.ReadSubTree,
		System.Security.AccessControl.RegistryRights.ReadKey);

foreach (string Keyname in rk.GetSubKeyNames())
{
	Console.WriteLine(Keyname);
}

Note 8: Set permited time for a user to login into Windows

private void setTimes()
{
	string usrn = usr_lb2.SelectedIndex.ToString();
	string argument = "net user" +usrn+" /times:Mo,7-21;Di,7-21;Mi,7-21;Do,7-21;Fr,7-21 ";
	Process.Start("cmd.exe", argument);

}

Note 9: Microsoft Word insert table before/after/at bookmark

Bookmark bookmark = oDoc.Bookmarks.OfType<Bookmark>().FirstOrDefault(b => b.Name == "textmarke");
if (bookmark != null)
{
   //vor der Textmarke
   oDoc.Tables.Add(oDoc.Range(bookmark.Start, bookmark.Start), 3 + rowCount, 4, ref oMissing, ref oMissing);

   //nach der Textmarke
   oDoc.Tables.Add(oDoc.Range(bookmark.End, bookmark.End), 3 + rowCount, 4, ref oMissing, ref oMissing);

   //anstelle der Textmarke
   //Achtung, die Textmarke existiert danach nicht mehr!!
   oDoc.Tables.Add(bookmark.Range, 3 + rowCount, 4, ref oMissing, ref oMissing);
}

Leave a Reply

Your email address will not be published. Required fields are marked *