Rob van der Woude's Scripting Pages
Powered by GeSHi

C# Code Snippets

The following collection of C# code snippets assumes .NET Framework 4.0 is installed.
Check the code comments if later versions of the .NET Framework are required.

  1. Get the program's path
  2. Get the program's version
  3. Get the program's class and namespace
  4. Get the program's command line arguments
  5. Get the program's required .NET Framework version
  6. List installed .NET Framework versions
  7. Get the highest installed .NET Framework version
  8. Restart the program
  9. Restart the program with elevated privileges
  10. Wait
  11. Convert decimal to binary, octal and hexadecimal
  12. Read redirected standard input
  13. Parse a string the way the command line is parsed
  14. Read text from clipboard
  15. HTML escape text
  16. Select multiple files
  17. Get a file's size
  18. Create a new temporary file
  19. List available scanners and their properties
  20. Take a screenshot
  21. Case insensitive List.Contains extension method
  22. DateTime.LimitToRange( earliest, latest ) extension method
  23. float.LimitToRange( min, max ) extension method
  24. int.LimitToRange( min, max ) extension method
  25. Font.IsFixedPitch and FontFamily.IsFixedPitch extension methods
  26. Calculate the date for Easter Sunday
  27. Julian date math
  28. Read text from a file on the web
  29. Check if MS Office is installed
  30. Convert RTF to plain text
  31. Search the web with Google
  32. Dynamically generate icons
  33. Send keystrokes to the active window
  34. Open Windows Update (or other) settings window
  35. Get window handle by its name/title
  36. Check if mouse is available

  37. Manage other program windows with P/Invoke

  38. Check if a window is minimized
  39. Get a window's size and position
  40. Move and resize a window
  41. Maximize, minimize or restore a window
  42. WindowState enumeration for ShowWindow and ShowWindowAsync functions
  43. Bring a window to the foreground
  44. Play PCM sound files (*.WAV)

1. Get the program's path

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;

 

2. Get the program's version

  1. string progver = System.Reflection.Assembly.GetExecutingAssembly( ).GetName( ).Version.ToString( );

 

3. Get the program's class and namespace

  1. Console.WriteLine( "Class     : {0}", System.Reflection.Assembly.GetEntryAssembly( ).EntryPoint.DeclaringType.Name );
  2. Console.WriteLine( "Namespace : {0}", System.Reflection.Assembly.GetEntryAssembly( ).EntryPoint.DeclaringType.Namespace );

 

4. Get the program's command line arguments

  1. // Skip( 1 ) removes the first argument, i.e. the program name; Skip( ) requires Linq
  2. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // arguments in array
  3. string allarguments = string.Join( " ", arguments ); // arguments in single line
  4. string commandline = System.Environment.CommandLine; // entire command line

 

5. Get the program's required .NET Framework version

  1. // Get the required .NET Framework version
  2. // By Fernando Gonzalez Sanchez on StackOverflow.com
  3. // https://stackoverflow.com/a/18623516
  4. object[] list = System.Reflection.Assembly.GetExecutingAssembly( ).GetCustomAttributes( true );
  5. var attribute = list.OfType<System.Runtime.Versioning.TargetFrameworkAttribute>( ).First( ); // requires Linq
  6. string frameworkname = attribute.FrameworkName;
  7. string frameworkdisplayname = attribute.FrameworkDisplayName;

 

6. List installed .NET Framework versions

  1. // Source of this code snippet:
  2. // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
  3.  
  4. // Opens the registry key for the .NET Framework entry.
  5. using ( Microsoft.Win32.RegistryKey ndpKey =
  6. 	Microsoft.Win32.RegistryKey.OpenRemoteBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, "" )
  7. 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  8. {
  9. 	// As an alternative, if you know the computers you will query are running .NET Framework 4.5 or later, you can use:
  10. 	// using ( Microsoft.Win32.RegistryKey ndpKey =
  11. 	// 	Microsoft.Win32.RegistryKey.OpenBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32 )
  12. 	// 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  13. 	foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
  14. 	{
  15. 		if ( versionKeyName.StartsWith( "v" ) )
  16. 		{
  17. 			Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
  18. 			string name = (string) versionKey.GetValue( "Version", "" );
  19. 			string sp = versionKey.GetValue( "SP", "" ).ToString( );
  20. 			string install = versionKey.GetValue( "Install", "" ).ToString( );
  21. 			if ( install == "" ) //no install info, must be later.
  22. 			{
  23. 				System.Console.WriteLine( versionKeyName + "  " + name );
  24. 			}
  25. 			else
  26. 			{
  27. 				if ( sp != "" && install == "1" )
  28. 				{
  29. 					System.Console.WriteLine( versionKeyName + "  " + name + "  SP" + sp );
  30. 				}
  31. 			}
  32. 			if ( name != "" )
  33. 			{
  34. 				continue;
  35. 			}
  36. 			foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
  37. 			{
  38. 				Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
  39. 				name = (string) subKey.GetValue( "Version", "" );
  40. 				if ( name != "" )
  41. 				{
  42. 					sp = subKey.GetValue( "SP", "" ).ToString( );
  43. 				}
  44. 				install = subKey.GetValue( "Install", "" ).ToString( );
  45. 				if ( install == "" ) //no install info, must be later.
  46. 				{
  47. 					System.Console.WriteLine( versionKeyName + "  " + name );
  48. 				}
  49. 				else
  50. 				{
  51. 					if ( sp != "" && install == "1" )
  52. 					{
  53. 						System.Console.WriteLine( "  " + subKeyName + "  " + name + "  SP" + sp );
  54. 					}
  55. 					else if ( install == "1" )
  56. 					{
  57. 						System.Console.WriteLine( "  " + subKeyName + "  " + name );
  58. 					}
  59. 				}
  60. 			}
  61. 		}
  62. 	}
  63. }

 

7. Get the highest installed .NET Framework version

  1. int rc = 0; // default return code if no .NET Framework is found
  2. System.Collections.Generic.List<string> installedversions = new System.Collections.Generic.List<string>( ); // list of all versions installed
  3. int[] highestversion = new int[] { 0, 0, 0, 0 }; // helper variable to determine which string represents the highest version
  4. // Get the list of installed .NET Framework versions from the registry, by Microsoft:
  5. // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
  6. using ( Microsoft.Win32.RegistryKey ndpKey =
  7. 	Microsoft.Win32.RegistryKey.OpenRemoteBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, "" )
  8. 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  9. {
  10. 	foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
  11. 	{
  12. 		if ( versionKeyName.StartsWith( "v" ) )
  13. 		{
  14. 			Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
  15. 			string name = (string) versionKey.GetValue( "Version", "" );
  16. 			if ( name == "" )
  17. 			{
  18. 				foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
  19. 				{
  20. 					Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
  21. 					name = (string) subKey.GetValue( "Version", "" );
  22. 					if ( name != "" )
  23. 					{
  24. 						installedversions.Add( name );
  25. 					}
  26. 				}
  27. 			}
  28. 			else
  29. 			{
  30. 				installedversions.Add( name );
  31. 			}
  32. 		}
  33. 	}
  34. }
  35. // Determine the highest version
  36. foreach ( string version in installedversions )
  37. {
  38. 	int[] version2 = version.Split( ".".ToCharArray( ) ).Select( x => System.Convert.ToInt32( x ) ).ToArray( );
  39. 	int minlength = System.Math.Min( version.Length, version2.Length );
  40. 	for ( int i = 0; i < minlength; i++ )
  41. 	{
  42. 		if ( highestversion[i] < System.Convert.ToInt32( version2[i] ) )
  43. 		{
  44. 			highestversion = version2;
  45. 			break;
  46. 		}
  47. 	}
  48. }
  49. // Write version string to screen
  50. System.Console.WriteLine( string.Join( ".", highestversion.Select( x => x.ToString( ) ).ToArray( ) ) ); // requires System.Linq
  51. // Return code is based on first 2 digits of highest version
  52. rc = 100 * highestversion[0] + highestversion[1];
  53. return rc;

 

8. Restart the program

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;
  4. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  5. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( );
  6. startinfo.FileName = programpath;
  7. startinfo.UseShellExecute = true;
  8. startinfo.Arguments = string.Join( " ", arguments );
  9. System.Diagnostics.Process.Start( startinfo );
  10. System.Environment.Exit( 0 ); // return code 0, change if required
  11. // Or for Windows Forms:
  12. // System.Windows.Forms.Application.Exit( );

 

9. Restart the program with elevated privileges

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;
  4. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  5. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( );
  6. startinfo.FileName = programpath;
  7. startinfo.UseShellExecute = true;
  8. startinfo.Verb = "runas";
  9. startinfo.Arguments = String.Join( " ", arguments );
  10. System.Diagnostics.Process.Start( startinfo );
  11. System.Environment.Exit( 0 ); // return code 0, change if required
  12. // Or for Windows Forms:
  13. // System.Windows.Forms.Application.Exit( );

 

10. Wait

  1. System.Threading.Thread.Sleep( 5000 ); // wait 5 seconds (5000 milliseconds)

 

11. Convert decimal to binary, octal and hexadecimal

  1. long dec = 9876543210;
  2. string bin = Convert.ToString( dec, 2 );
  3. string oct = Convert.ToString( dec, 8 );
  4. string hex = Convert.ToString( dec, 16 );
  5. Console.WriteLine( "Decimal     : {0}", dec );
  6. Console.WriteLine( "Binary      : {0}", bin );
  7. Console.WriteLine( "Octal       : 0{0}", oct );
  8. Console.WriteLine( "Hexadecimal : 0x{0}", hex.ToUpper( ) );

 

12. Read redirected standard input

  1. string input = string.Empty;
  2. if ( System.Console.IsInputRedirected ) // requires .NET Framework 4.5
  3. {
  4. 	System.Console.OpenStandardInput( );
  5. 	input = System.Console.In.ReadToEnd( );
  6. }

 

13. Parse a string the way the command line is parsed

  1. // Code by Atif Aziz on StackOverflow.com:
  2. // https://stackoverflow.com/a/749653
  3. [DllImport( "shell32.dll", SetLastError = true )]
  4. static extern IntPtr CommandLineToArgvW( [MarshalAs( UnmanagedType.LPWStr )] string lpCmdLine, out int pNumArgs );
  5.  
  6. public static string[] CommandLineToArgs( string commandLine )
  7. {
  8. int argc;
  9. var argv = CommandLineToArgvW( commandLine, out argc );
  10. if ( argv == IntPtr.Zero )
  11. {
  12. 	throw new System.ComponentModel.Win32Exception( );
  13. }
  14. try
  15. {
  16. 	var args = new string[argc];
  17. 	for ( var i = 0; i < args.Length; i++ )
  18. 	{
  19. 		var p = Marshal.ReadIntPtr( argv, i * IntPtr.Size );
  20. 		args[i] = Marshal.PtrToStringUni( p );
  21. 	}
  22. 	return args;
  23. }
  24. finally
  25. {
  26. 	Marshal.FreeHGlobal( argv );
  27. }

 

14. Read text from clipboard

  1. string cliptext = string.Empty;
  2. if ( System.Windows.Forms.Clipboard.ContainsText( ) )
  3. {
  4. 	clipText = System.Windows.Forms.Clipboard.GetText( );
  5. }

 

15. HTML escape text

  1. string unescapedtext = "4 > 3";
  2. string escapedtext = System.Net.WebUtility.HtmlEncode( unescapedtext );

 

16. Select multiple files

  1. // In DOS this works: DIR *.doc *.xls
  2. // But in C# this does NOT work:
  3. // Directory.GetFiles( folder, "*.doc *.xls" )
  4. // Instead use:
  5. Directory.GetFiles( folder, "*.*" ).Where( f => f.EndsWith( ".doc" ) || f.EndsWith( ".xls" ) )

 

17. Get a file's size

  1. Single filesize = new System.IO.FileInfo( filepath ).Length; // specify filepath

 

18. Create a new temporary file

  1. // This will create a new temporary file and return its path
  2. string newtempfile = System.IO.Path.GetTempFileName( );

 

19. List available scanners and their properties

  1. // Add a reference to the COM library "Microsoft Windows Image Acquisition" (WIA),
  2. // and set its property "Embed Interop Types" to false
  3. // https://ourcodeworld.com/articles/read/382/creating-a-scanning-application-in-winforms-with-csharp
  4.  
  5. int columnwidth = 0;
  6. WIA.DeviceManager devicemanager = new WIA.DeviceManager( );
  7. foreach ( WIA.DeviceInfo devinfo in devicemanager.DeviceInfos )
  8. {
  9. 	if ( devinfo.Type == WIA.WiaDeviceType.ScannerDeviceType ) // scanners only
  10. 	{
  11. 		foreach ( WIA.Property prop in devinfo.Properties )
  12. 		{
  13. 			columnwidth = System.Math.Max( columnwidth, prop.Name.Length );
  14. 		}
  15. 	}
  16. }
  17.  
  18. foreach ( WIA.DeviceInfo devinfo in devicemanager.DeviceInfos )
  19. {
  20. 	if ( devinfo.Type == WIA.WiaDeviceType.ScannerDeviceType ) // scanners only
  21. 	{
  22. 		foreach ( WIA.Property prop in devinfo.Properties )
  23. 		{
  24. 			System.Console.WriteLine( "{0,-" + columnwidth + "}    {1}", prop.Name, prop.get_Value( ) );
  25. 		}
  26. 	}
  27. 	System.Console.WriteLine( );
  28. }

 

20. Take a screenshot

  1. // Take a screenshot
  2. // By Ali Hamdar (http://alihamdar.com/)
  3. // http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/79efecc4-fa6d-4078-afe4-bb1379bb968b
  4.  
  5. // Default values for full screen
  6. int width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
  7. int height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
  8. int top = 0;
  9. int left = 0;
  10.  
  11. System.Drawing.Bitmap printscreen = new System.Drawing.Bitmap( width, height );
  12. System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage( printscreen as Image );
  13. graphics.CopyFromScreen( top, left, 0, 0, printscreen.Size );
  14. printscreen.Save( outputfile, imagetype );

 

21. Case insensitive List.Contains( key ) extension method

  1. public static class ExtensionMethods
  2. {
  3. 	public static bool ContainsCI( this System.Collections.Generic.List<string> value, string key )
  4. 	{
  5. 		return value.Any( k => k.Equals( key, System.StringComparison.OrdinalIgnoreCase ) ); // requires Linq
  6. 	}
  7. }

 

22. DateTime.LimitToRange( earliest, latest ) extension method

  1. public static class ExtensionMethods
  2. {
  3. 	public static System.DateTime LimitToRange( this System.DateTime value, System.DateTime earliest, System.DateTime latest )
  4. 	{
  5. 		if ( System.DateTime.Compare( value, earliest ) < 0 )
  6. 		{
  7. 			return earliest;
  8. 		}
  9. 		if ( System.DateTime.Compare( value, latest ) > 0 )
  10. 		{
  11. 			return latest;
  12. 		}
  13. 		return value;
  14. 	}

 

23. float.LimitToRange( min, max ) extension method

  1. 	public static float LimitToRange( this float value, float inclusiveMinimum, float inclusiveMaximum )
  2. 	{
  3. 		if ( value < inclusiveMinimum )
  4. 		{
  5. 			return inclusiveMinimum;
  6. 		}
  7. 		if ( value > inclusiveMaximum )
  8. 		{
  9. 			return inclusiveMaximum;
  10. 		}
  11. 		return value;
  12. 	}

 

24. int.LimitToRange( min, max ) extension method

  1. 	// Extension by "dtb" on StackOverflow.com:
  2. 	// https://stackoverflow.com/a/3176628
  3. 	public static int LimitToRange( this int value, int inclusiveMinimum, int inclusiveMaximum )
  4. 	{
  5. 		if ( value < inclusiveMinimum )
  6. 		{
  7. 			return inclusiveMinimum;
  8. 		}
  9. 		if ( value > inclusiveMaximum )
  10. 		{
  11. 			return inclusiveMaximum;
  12. 		}
  13. 		return value;
  14. 	}
  15. }

 

25. Font.IsFixedPitch and FontFamily.IsFixedPitch extension methods

  1. public static class ExtensionMethods
  2. {
  3. 	public static bool IsFixedPitch( this System.Drawing.FontFamily value )
  4. 	{
  5. 		System.Drawing.Font font = new System.Drawing.Font( value, 12, System.Drawing.FontStyle.Regular );
  6. 		return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", font ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", font ) );
  7. 	}
  8.  
  9. 	public static bool IsFixedPitch( this System.Drawing.Font value )
  10. 	{
  11. 		// Inspired by a tip from Hans passant
  12. 		// https://stackoverflow.com/q/21965321
  13. 		return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", value ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", value ) );
  14. 	}
  15. }

 

26. Calculate the date for Easter Sunday

  1. // Easter is at first Sunday after the first full moon at or after the Spring equinox (21 March)
  2. // Calculation explained: https://www.timeanddate.com/calendar/determining-easter-date.html
  3. int year = DateTime.Now.Year # or choose any year (100+), it doesn't have to be an int, string is fine too
  4. // For Easter calculations, the Spring equinox is always assumed to be at 21 March
  5. DateTime springequinox = DateTime.Parse( string.Format( "{0}-03-21", year ) );
  6. // Calculate full moon cycles to first full moon after Spring equinox of specified year
  7. int fullcycles = (int)Math.Ceiling( springequinox.Subtract( referencefullmoon ).Days / mooncycleindays );
  8. // Date of first full moon after Spring equinox of specified year
  9. DateTime fullmoonafterequinox = referencefullmoon.AddDays( fullcycles * mooncycleindays );
  10. // First Sunday following first full moon at or after Spring equinox of specified year
  11. DateTime eastersunday = fullmoonafterequinox.AddDays( 7 - (int)fullmoonafterequinox.DayOfWeek ).Date;

 

27. Julian date math

  1. // Convert today's date to Julian date by David Yaw: https://stackoverflow.com/a/5254812
  2. double juliandate = System.DateTime.Today.ToOADate( ) + 2415018.5;
  3. // or (see https://en.wikipedia.org/wiki/Julian_day#Variants for details):
  4. double juliandate = System.DateTime.Today.Date.Ticks / 864000000000 + 1721425.5;
  5.  
  6. //Convert Julian date back to Gregorian date:
  7. System.DateTime gregoriandate = System.DateTime.FromOADate( juliandate - 2415018.5 );
  8. // or:
  9. System.DateTime gregoriandate = System.DateTime.Parse( "0001-01-01" ).AddTicks( (long)( juliandate - 1721425.5 ) * 864000000000 );

 

28. Read text from a file on the web

  1. string url = "https://www.example.com/example.txt"
  2. // The next couple of ServicePointManager lines are required for secure connections only
  3. System.Net.ServicePointManager.Expect100Continue = true;
  4. System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12;
  5. System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Ssl3;
  6. System.Net.WebClient webclient = new System.Net.WebClient( );
  7. string text = webclient.DownloadString( url );
  8. webclient.Dispose( );

 

29. Check if MS Office is installed

  1. // This will work only for true MSI-based Office installations, not for click-to-run installations
  2. (bool) isAccessInstalled     = ( Type.GetTypeFromProgID( "Access.Application" )     != null );
  3. (bool) isExcelInstalled      = ( Type.GetTypeFromProgID( "Excel.Application" )      != null );
  4. (bool) isMSGraphInstalled    = ( Type.GetTypeFromProgID( "MSGraph.Application" )    != null );
  5. (bool) isOutlookInstalled    = ( Type.GetTypeFromProgID( "Outlook.Application" )    != null );
  6. (bool) isPowerPointInstalled = ( Type.GetTypeFromProgID( "PowerPoint.Application" ) != null );
  7. (bool) isWordInstalled       = ( Type.GetTypeFromProgID( "Word.Application" )       != null );

 

30. Convert RTF to plain text

  1. // Use a hidden RichTextBox to convert RTF to plain text, by Wendy Zang
  2. // https://social.msdn.microsoft.com/Forums/vstudio/en-US/6e56af9b-d7d3-49f3-9ec4-80edde3fe54b/reading-modifying-rtf-files?forum=csharpgeneral#a64345e9-cfcb-43be-ab18-c08fae02cb2a
  3. string rtffile = "D:\\folder\\rtffile.rtf";
  4. System.Windows.Forms.RichTextBox rtbox = new System.Windows.Forms.RichTextBox( );
  5. string rtftext = System.IO.File.ReadAllText( rtffile );
  6. rtbox.Rtf = rtftext;
  7. string plaintext = rtbox.Text;
  8. Console.WriteLine( plaintext );

 

31. Search the web with Google

  1. // This will open search results from Google in your default browser
  2. string query = System.Uri.EscapeDataString( "whatever it is I'm looking for" );
  3. string domain = "microsoft.com"; // search only on this domain
  4. if ( !string.IsNullOrWhiteSpace( domain ) )
  5. {
  6. 	query += string.Format( "+site:{0}", domain );
  7. }
  8. string url = string.Format( "https://www.google.com/search?q={0}&btnI=745&pws=0", query );
  9. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( url );
  10. System.Diagnostics.Process.Start( startinfo );

 

32. Dynamically generate icons

  1. // Dynamically generate icons; based on code by Joshua Flanagan on CodeProject.com
  2. // https://www.codeproject.com/Articles/7122/Dynamically-Generating-Icons-safely
  3. // This code will create an icon, draw a circle and fill it with backgroundcolor, and place some text (not too long) in the center
  4. public System.Drawing.Icon CreateIcon( string text, System.Drawing.Font font, System.Drawing.Brush foregroundcolor, System.Drawing.Brush backgroundcolor )
  5. {
  6. 	System.Drawing.Icon icon = null;
  7. 	System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( 16, 16 );
  8. 	using ( System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage( bitmap ) )
  9. 	{
  10. 		graphic.FillEllipse( backgroundcolor, 0, 0, 16, 16 ); // Create circle and fill it with  background color
  11. 		System.Drawing.SizeF textsize = graphic.MeasureString( text, font ); // Determine the size and position of the text
  12. 		System.Single x = System.Convert.ToSingle( System.Math.Floor( ( bitmap.Width - textsize.Width ) / 2 ) );
  13. 		System.Single y = System.Convert.ToSingle( System.Math.Ceiling( ( bitmap.Height - textsize.Height ) / 2 ) );
  14. 		graphic.DrawString( text, font, foregroundcolor, x, y, System.Drawing.StringFormat.GenericDefault ); // Generate an image of the text
  15. 		icon = System.Drawing.Icon.FromHandle( bitmap.GetHicon( ) );
  16. 	}
  17. 	return icon;
  18. }

 

33. Send keystrokes to the active window

  1. // For more details, including codes for special keys, see:
  2. // https://docs.microsoft.com/dotnet/api/system.windows.forms.sendkeys.send
  3. System.Windows.Forms.SendKeys.SendWait( string keys );

 

34. Open Windows Update (or other) settings window

  1. // Open Windows Update settings; more URIs for specific settings can be found at
  2. // https://docs.microsoft.com/en-us/windows/uwp/launch-resume/launch-settings-app#ms-settings-uri-scheme-reference
  3. System.Diagnostics.Process.Start( "ms-settings:windowsupdate" );

 

35. Get window handle by its name/title

  1. // Source: https://stackoverflow.com/a/13547659
  2. public static IntPtr WinGetHandle( string wName )
  3. {
  4. 	IntPtr hWnd = IntPtr.Zero;
  5. 	foreach ( Process pList in Process.GetProcesses( ) )
  6. 	{
  7. 		if ( pList.MainWindowTitle.Contains( wName ) )
  8. 		{
  9. 			hWnd = pList.MainWindowHandle;
  10. 		}
  11. 	}
  12. 	return hWnd; // Should contain the handle but may be zero if the title doesn't match
  13. }

 

36. Check if mouse is available

  1. // GetSystemMetrics( 43 ) ALWAYS returns the ACTUAL total number of mouse buttons
  2. bool mousepresent = ( GetSystemMetrics( 43 ) > 0 );
  3.  
  4. // Add the following DLL Import in your Program class
  5. [System.Runtime.InteropServices.DllImport( "user32.dll" )]
  6. static extern int GetSystemMetrics( int smIndex );

 

Manage other program windows with P/Invoke

The next 6 code snippets use unmanaged code to manipulate other programs' windows by their window handle (see previous item).
The last snippet uses unmanaged code to play PCM sound files (*.WAV), either synchronously or asynchronously, only once or continuously.

For more details search for these functions on PInvoke.net.

Don't forget to include using System.Runtime.InteropServices; in your code.

37. Check if a window is minimized

  1. [DllImport( "user32.dll" )]
  2. [return: MarshalAs( UnmanagedType.Bool )]
  3. static extern bool IsIconic( IntPtr hWnd ); // true if window is minimized

 

38. Get a window's size and position

  1. [DllImport( "user32.dll", SetLastError = true )]
  2. [return: MarshalAs( UnmanagedType.Bool )]
  3. static extern bool GetWindowRect( IntPtr hWnd, ref RECT lpRect ); // RECT lpRect must be initialized before calling this function
  4.  
  5. [StructLayout( LayoutKind.Sequential )]
  6. public struct RECT
  7. {
  8. 	public int Left;
  9. 	public int Top;
  10. 	public int Right;
  11. 	public int Bottom;
  12. }

 

39. Move and resize a window

  1. [DllImport( "user32.dll" )]
  2. public static extern bool MoveWindow( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint );

 

40. Maximize, minimize, hide or restore a window

  1. private const int SW_HIDE = 0;
  2. private const int SW_SHOWNORMAL = 1;
  3. private const int SW_SHOWMINIMIZED = 2;
  4. private const int SW_SHOWMAXIMIZED = 3;
  5.  
  6. [DllImport( "user32.dll" )]
  7. private static extern bool ShowWindow( IntPtr hWnd, int nCmdShow ); // Use one of the constants for nCmdShow to maximize, minimize or restore the window
  8.  
  9. [DllImport( "user32.dll" )]
  10. private static extern bool ShowWindowAsync( IntPtr hWnd, int nCmdShow ); // Same function but asynchronous

 

41. WindowState enumeration for ShowWindow and ShowWindowAsync functions

  1. // Instead of the separate constants for the ShowWindow and ShowWindowAsync functions you can use an enumeration.
  2. // Source: http://pinvoke.net/default.aspx/user32/ShowState.html
  3. public enum ShowState
  4. {
  5. 	SW_HIDE = 0,
  6. 	SW_SHOWNORMAL = 1,
  7. 	SW_NORMAL = 1,
  8. 	SW_SHOWMINIMIZED = 2,
  9. 	SW_SHOWMAXIMIZED = 3,
  10. 	SW_MAXIMIZE = 3,
  11. 	SW_SHOWNOACTIVATE = 4,
  12. 	SW_SHOW = 5,
  13. 	SW_MINIMIZE = 6,
  14. 	SW_SHOWMINNOACTIVE = 7,
  15. 	SW_SHOWNA = 8,
  16. 	SW_RESTORE = 9,
  17. 	SW_SHOWDEFAULT = 10,
  18. 	SW_FORCEMINIMIZE = 11,
  19. 	SW_MAX = 11
  20. }

 

42. Bring a window to the foreground

  1. // Will not immediately change the foreground window while another window receives input
  2. [DllImport( "user32.dll" )]
  3. public static extern bool SetForegroundWindow( IntPtr hWnd );

 

43. Play PCM sound files (*.WAV)

  1. // Source: http://pinvoke.net/default.aspx/winmm/PlaySound.html
  2.  
  3. // Play once and wait:
  4. PlaySound( wav_file, UIntPtr.Zero, (uint) SoundFlags.SND_FILENAME );
  5.  
  6. // Play once, don't wait:
  7. PlaySound( wav_file, UIntPtr.Zero, (uint)( SoundFlags.SND_FILENAME | SoundFlags.SND_ASYNC ) );
  8.  
  9. // Play continuously until next PlaySound command, don't wait:
  10. PlaySound( wav_file, UIntPtr.Zero, (uint)( SoundFlags.SND_FILENAME | SoundFlags.SND_ASYNC | SoundFlags.SND_LOOP ) );
  11.  
  12. // Abort continuous playing:
  13. PlaySound( null, UIntPtr.Zero, 0 );
  14.  
  15. // Required DLL import:
  16. [DllImport( "winmm.dll", SetLastError = true )]
  17. static extern bool PlaySound( string pszSound, UIntPtr hmod, uint fdwSound );
  18.  
  19. // Required Enum:
  20. public enum SoundFlags
  21. {
  22. 	/// <summary>play synchronously (default)</summary>
  23. 	SND_SYNC = 0x0000,
  24. 	/// <summary>play asynchronously</summary>
  25. 	SND_ASYNC = 0x0001,
  26. 	/// <summary>silence (!default) if sound not found</summary>
  27. 	SND_NODEFAULT = 0x0002,
  28. 	/// <summary>pszSound points to a memory file</summary>
  29. 	SND_MEMORY = 0x0004,
  30. 	/// <summary>loop the sound until next sndPlaySound</summary>
  31. 	SND_LOOP = 0x0008,
  32. 	/// <summary>don't stop any currently playing sound</summary>
  33. 	SND_NOSTOP = 0x0010,
  34. 	/// <summary>Stop Playing Wave</summary>
  35. 	SND_PURGE = 0x40,
  36. 	/// <summary>The pszSound parameter is an application-specific alias in the registry. You can combine this flag with the SND_ALIAS or SND_ALIAS_ID flag to specify an application-defined sound alias.</summary>
  37. 	SND_APPLICATION = 0x80,
  38. 	/// <summary>don't wait if the driver is busy</summary>
  39. 	SND_NOWAIT = 0x00002000,
  40. 	/// <summary>name is a registry alias</summary>
  41. 	SND_ALIAS = 0x00010000,
  42. 	/// <summary>alias is a predefined id</summary>
  43. 	SND_ALIAS_ID = 0x00110000,
  44. 	/// <summary>name is file name</summary>
  45. 	SND_FILENAME = 0x00020000,
  46. 	/// <summary>name is resource name or atom</summary>
  47. 	SND_RESOURCE = 0x00040004
  48. }

 


page last modified: 2024-02-26; loaded in 0.0510 seconds