Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for back2base.cs

(view source code of back2base.cs as plain text)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Windows.Forms;
  7.  
  8.  
  9. namespace Back2Base
  10. {
  11. 	static class Back2BaseProgram
  12. 	{
  13. 		static readonly string progver = "1.00";
  14.  
  15. 		static readonly int screenwidth = Screen.PrimaryScreen.WorkingArea.Width;
  16. 		static readonly int screenheight = Screen.PrimaryScreen.WorkingArea.Height;
  17.  
  18. 		static bool includeminimized = false;
  19. 		static bool includeanonymous = false;
  20.  
  21.  
  22. 		[STAThread]
  23. 		static int Main( )
  24. 		{
  25. 			Application.EnableVisualStyles( );
  26. 			Application.SetCompatibleTextRenderingDefault( false );
  27.  
  28.  
  29. 			#region Parse Command Line
  30.  
  31. 			foreach ( string arg in Environment.CommandLine.Split( ' ' ).Skip( 1 ) )
  32. 			{
  33. 				switch ( arg.ToUpper( ) )
  34. 				{
  35. 					case "":
  36. 						break;
  37. 					case "/?":
  38. 						return ShowHelp( );
  39. 					case "/IA":
  40. 						if ( includeanonymous )
  41. 						{
  42. 							return ShowHelp( "Duplicate command line switch /IA" );
  43. 						}
  44. 						includeanonymous = true;
  45. 						break;
  46. 					case "/IM":
  47. 						if ( includeminimized )
  48. 						{
  49. 							return ShowHelp( "Duplicate command line switch /IM" );
  50. 						}
  51. 						includeminimized = true;
  52. 						break;
  53. 					default:
  54. 						return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  55. 				}
  56. 			}
  57.  
  58. 			#endregion Parse Command Line
  59.  
  60.  
  61. 			// List active windows
  62. 			GetDesktopWindowHandlesAndTitles( out windows );
  63.  
  64.  
  65. 			#region Restore Minimized Windows
  66.  
  67. 			// First restore/maximize any minimized window(s) that should be included
  68. 			foreach ( IntPtr handle in windows.Keys )
  69. 			{
  70. 				if ( windows[handle] != "(no title)" || includeanonymous )
  71. 				{
  72. 					if ( !IsIconic( handle ) || includeminimized )
  73. 					{
  74. 						if ( IsIconic( handle ) && includeminimized )
  75. 						{
  76. 							ShowWindow( handle, SW_SHOWMAXIMIZED );
  77. 							//ShowWindow( handle, SW_SHOWMAXIMIZED );
  78. 						}
  79. 					}
  80. 				}
  81. 			}
  82.  
  83. 			#endregion Restore Minimized Windows
  84.  
  85.  
  86. 			#region Move Windows to Primary Monitor
  87.  
  88. 			// Next move the window(s) to the primary monitor
  89. 			int count = 0;
  90.  
  91. 			foreach ( IntPtr handle in windows.Keys )
  92. 			{
  93. 				if ( windows[handle] != "(no title)" || includeanonymous )
  94. 				{
  95. 					if ( !IsIconic( handle ) || includeminimized )
  96. 					{
  97. 						RECT rect = new RECT( );
  98. 						if ( GetWindowRect( handle, ref rect ) )
  99. 						{
  100. 							if ( ( rect.Left > screenwidth || rect.Right < 20 || rect.Top > screenheight || rect.Bottom < 20 ) && ( rect.Left != 0 && rect.Top != 0 ) )
  101. 							{
  102. 								int width = rect.Right - rect.Left;
  103. 								int height = rect.Bottom - rect.Top;
  104. 								bool repaint = true;
  105. 								if ( MoveWindow( handle, 0, 0, width, height, repaint ) )
  106. 								{
  107. 									count += 1;
  108. 								}
  109. 							}
  110. 						}
  111. 					}
  112. 				}
  113. 			}
  114.  
  115. 			#endregion Move Windows to Primary Monitor
  116.  
  117.  
  118. 			return count;
  119. 		}
  120.  
  121.  
  122. 		#region Check If Minimized
  123.  
  124. 		[DllImport( "user32.dll" )]
  125. 		[return: MarshalAs( UnmanagedType.Bool )]
  126. 		static extern bool IsIconic( IntPtr hWnd ); // true if window is minimized
  127.  
  128. 		#endregion Check If Minimized
  129.  
  130.  
  131. 		#region Get Window Size
  132.  
  133. 		// Get window position and size
  134. 		// https://stackoverflow.com/a/1434577
  135. 		[DllImport( "user32.dll", SetLastError = true )]
  136. 		[return: MarshalAs( UnmanagedType.Bool )]
  137. 		static extern bool GetWindowRect( IntPtr hWnd, ref RECT lpRect );
  138. 		[StructLayout( LayoutKind.Sequential )]
  139.  
  140.  
  141. 		public struct RECT
  142. 		{
  143. 			public int Left;
  144. 			public int Top;
  145. 			public int Right;
  146. 			public int Bottom;
  147. 		}
  148.  
  149. 		#endregion Get Window Size
  150.  
  151.  
  152. 		#region List Desktop Windows
  153.  
  154. 		// Based on code by Rod Stephens
  155. 		// List desktop windows in C#
  156. 		// http://csharphelper.com/blog/2016/08/list-desktop-windows-in-c/
  157.  
  158. 		[DllImport( "user32.dll" )]
  159. 		[return: MarshalAs( UnmanagedType.Bool )]
  160. 		private static extern bool IsWindowVisible( IntPtr hWnd );
  161.  
  162. 		[DllImport( "user32.dll", EntryPoint = "GetWindowText",
  163. 		ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true )]
  164. 		private static extern int GetWindowText( IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount );
  165.  
  166. 		[DllImport( "user32.dll", EntryPoint = "EnumDesktopWindows",
  167. 		ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true )]
  168. 		private static extern bool EnumDesktopWindows( IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam );
  169.  
  170. 		// Define the callback delegate's type.
  171. 		private delegate bool EnumDelegate( IntPtr hWnd, int lParam );
  172.  
  173. 		// Save window titles and handles in Dictionary
  174. 		private static Dictionary<IntPtr, string> windows;
  175.  
  176. 		// Return a list of the desktop windows' handles and titles.
  177. 		public static void GetDesktopWindowHandlesAndTitles( out Dictionary<IntPtr, string> windowslist )
  178. 		{
  179. 			windowslist = new Dictionary<IntPtr, string>( );
  180.  
  181. 			if ( !EnumDesktopWindows( IntPtr.Zero, FilterCallback, IntPtr.Zero ) )
  182. 			{
  183. 				windowslist = null;
  184. 			}
  185. 			else
  186. 			{
  187. 				windowslist = windows;
  188. 			}
  189. 		}
  190.  
  191.  
  192. 		// We use this function to filter windows
  193. 		// This version selects visible windows that aren't minimized
  194. 		private static bool FilterCallback( IntPtr hWnd, int lParam )
  195. 		{
  196. 			// Get the window's title
  197. 			StringBuilder sb_title = new StringBuilder( 1024 );
  198. 			int _ = GetWindowText( hWnd, sb_title, sb_title.Capacity );
  199. 			string title = sb_title.ToString( );
  200.  
  201. 			// If the window is visible and has a title, save it.
  202. 			if ( IsWindowVisible( hWnd ) )
  203. 			{
  204. 				if ( string.IsNullOrEmpty( title ) )
  205. 				{
  206. 					title = "(no title)";
  207. 				}
  208. 				windows.Add( hWnd, title );
  209. 			}
  210.  
  211. 			// Return true to indicate that we should continue enumerating windows
  212. 			return true;
  213. 		}
  214.  
  215. 		#endregion List Desktop Windows
  216.  
  217.  
  218. 		#region Move Window
  219.  
  220. 		// Based on code by Roberto Luis Bisb\u00E9
  221. 		// Moving windows programatically with Windows API, the path to WinResize
  222. 		// https://rlbisbe.net/2013/11/19/moving-windows-programatically-with-windows-api-the-path-to-winresize/
  223.  
  224. 		[DllImport( "user32.dll" )]
  225. 		public static extern bool MoveWindow( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint );
  226.  
  227. 		#endregion Move Window
  228.  
  229.  
  230. 		#region Restore Window
  231.  
  232. 		// private const int SW_SHOWNORMAL = 1;
  233. 		// private const int SW_SHOWMINIMIZED = 2;
  234. 		private const int SW_SHOWMAXIMIZED = 3;
  235.  
  236.  
  237. 		[DllImport( "user32.dll" )]
  238. 		private static extern bool ShowWindow( IntPtr hWnd, int nCmdShow );
  239.  
  240.  
  241. 		[DllImport( "user32.dll" )]
  242. 		private static extern bool ShowWindowAsync( IntPtr hWnd, int nCmdShow );
  243.  
  244. 		#endregion Restore Window
  245.  
  246.  
  247. 		#region Error handling
  248.  
  249. 		public static int ShowHelp( params string[] errmsg )
  250. 		{
  251. 			string helptext = string.Empty;
  252. 			string title = "Back2Base,  Version " + progver;
  253. 			MessageBoxIcon icon = MessageBoxIcon.Information;
  254.  
  255. 			#region Error Message
  256.  
  257. 			if ( errmsg.Length > 0 )
  258. 			{
  259. 				List<string> errargs = new List<string>( errmsg );
  260. 				errargs.RemoveAt( 0 );
  261. 				helptext += "\nERROR:\t" + string.Format( errmsg[0], errargs.ToArray( ) ) + "\n\n";
  262. 				title = "Error";
  263. 				icon = MessageBoxIcon.Error;
  264. 			}
  265.  
  266. 			#endregion Error Message
  267.  
  268.  
  269. 			#region Help Text
  270.  
  271. 			/*
  272. 			Back2Base.exe,  Version 1.00
  273. 			Move out-of-sight windows back to the primary screen
  274.  
  275. 			Usage:   Back2Base  [ /IA ]  [ /IM ]
  276.  
  277. 			Options: /IA	Include Anonymous windows, i.e. those without title
  278. 			         /IM    Include Minimized windows
  279.  
  280. 			Credits:
  281. 			Get window position and size
  282. 			https://stackoverflow.com/a/1434577
  283.  
  284. 			List desktop windows based on code by Rod Stephens
  285. 			http://csharphelper.com/blog/2016/08/list-desktop-windows-in-c/
  286.  
  287. 			Moving windows based on code by Roberto Luis Bisb\u00E9
  288. 			https://rlbisbe.net/2013/11/19/moving-windows-programatically-with-windows-api-the-path-to-winresize/
  289.  
  290. 			Notes:
  291. 			This is a GUI version of CatchStrayWindows.exe; the only visible output will be error messages.
  292. 			Return code equals number of moved windows, or -1 in case of errors.
  293.  
  294. 			Written by Rob van der Woude
  295. 			https://www.robvanderwoude.com
  296. 			*/
  297.  
  298. 			#endregion Help Text
  299.  
  300.  
  301. 			#region Display Help Text
  302.  
  303. 			helptext += "Back2Base.exe,  Version " + progver;
  304. 			helptext += "\nMove out-of-sight windows back to the primary screen";
  305. 			helptext += "\n\nOptions:\n======\n\n/IA\tInclude Anonymous windows, i.e. those without title";
  306. 			helptext += "\n/IM\tInclude Minimized windows";
  307. 			helptext += "\n\nCredits:\n=====\n\nGet window position and size:";
  308. 			helptext += "\nhttps://stackoverflow.com/a/1434577";
  309. 			helptext += "\n\nList desktop windows based on code by Rod Stephens:";
  310. 			helptext += "\nhttp://csharphelper.com/blog/2016/08/list-desktop-windows-in-c/";
  311. 			helptext += "\n\nMoving windows based on code by Roberto Luis Bisb\u00E9:";
  312. 			helptext += "\nhttps://rlbisbe.net/2013/11/19/moving-windows-programatically-with-windows-api-the-path-to-winresize/";
  313. 			helptext += "\n\nNotes:\n====\n\nThis is a GUI version of CatchStrayWindows.exe; the only visible output will be error messages.";
  314. 			helptext += "\n\nReturn code equals number of moved windows, or -1 in case of errors.";
  315. 			helptext += "\n\nWritten by Rob van der Woude";
  316. 			helptext += "\nhttps://www.robvanderwoude.com";
  317.  
  318. 			MessageBox.Show( helptext, title, MessageBoxButtons.OK, icon, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly | MessageBoxOptions.ServiceNotification );
  319.  
  320. 			#endregion Display Help Text
  321.  
  322. 			return -1;
  323. 		}
  324.  
  325. 		#endregion Error handling
  326. 	}
  327. }
  328.  

page last modified: 2024-04-16; loaded in 0.0162 seconds