Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for consolestate.cs

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4.  
  5.  
  6. namespace RobvanderWoude
  7. {
  8. 	class ConsoleState
  9. 	{
  10. 		static string progver = "2.00";
  11.  
  12.  
  13. 		#region Global Variables
  14.  
  15. 		static bool debugmode = false;
  16. 		static bool hidewindow = false;
  17. 		static bool showwindow = false;
  18. 		static bool activatewindow = true;
  19. 		static bool maximizewindow = false;
  20. 		static bool minimizewindow = false;
  21. 		static bool normalwindow = false;
  22.  
  23. 		#endregion Global Variables
  24.  
  25.  
  26. 		static int Main( string[] args )
  27. 		{
  28. 			#region Parse Command Line
  29.  
  30. 			if ( args.Length == 0 )
  31. 			{
  32. 				if ( IsIconic( GetConsoleWindow( ) ) )
  33. 				{
  34. 					return 1; // window is minimized
  35. 				}
  36. 				else if ( IsWindowVisible( GetConsoleWindow( ) ) )
  37. 				{
  38. 					return 0; // window is visible
  39. 				}
  40. 				else
  41. 				{
  42. 					return 2; // window is hidden
  43. 				}
  44. 			}
  45. 			else
  46. 			{
  47. 				foreach ( string arg in args )
  48. 				{
  49. 					string key = arg;
  50. 					string val = String.Empty;
  51. 					if ( arg.IndexOfAny( ":=".ToCharArray( ) ) > 0 )
  52. 					{
  53. 						key = arg.Substring( 0, arg.IndexOfAny( ":=".ToCharArray( ) ) );
  54. 						val = arg.Substring( arg.IndexOfAny( ":=".ToCharArray( ) ) + 1 );
  55. 					}
  56. 					switch ( key.ToUpper( ) )
  57. 					{
  58. 						case "/?":
  59. 							return ShowHelp( );
  60. 						case "/D":
  61. 						case "/DEBUG":
  62. 							debugmode = true;
  63. 							break;
  64. 						case "/HIDE":
  65. 							if ( hidewindow )
  66. 							{
  67. 								return ShowHelp( "Duplicate command line switch /HIDE" );
  68. 							}
  69. 							if ( showwindow )
  70. 							{
  71. 								return ShowHelp( "Invalid combination of command line switches /HIDE, /SHOW and/or /TRAY" );
  72. 							}
  73. 							hidewindow = true;
  74. 							break;
  75. 						case "/MAX":
  76. 						case "/MAXIMIZE":
  77. 							if ( maximizewindow )
  78. 							{
  79. 								return ShowHelp( "Duplicate command line switch /MAX" );
  80. 							}
  81. 							if ( minimizewindow || normalwindow )
  82. 							{
  83. 								return ShowHelp( "Invalid combination of command line switches /MAX, /MIN and/or /NORMAL" );
  84. 							}
  85. 							maximizewindow = true;
  86. 							break;
  87. 						case "/MIN":
  88. 						case "/MINIMIZE":
  89. 							if ( minimizewindow )
  90. 							{
  91. 								return ShowHelp( "Duplicate command line switch /MIN" );
  92. 							}
  93. 							if ( maximizewindow || normalwindow )
  94. 							{
  95. 								return ShowHelp( "Invalid combination of command line switches /MAX, /MIN and/or /NORMAL" );
  96. 							}
  97. 							minimizewindow = true;
  98. 							break;
  99. 						case "/NOACT":
  100. 						case "/NOACTIVE":
  101. 						case "/NOACTIVATE":
  102. 						case "/DONTACTIVATE":
  103. 							if ( !activatewindow )
  104. 							{
  105. 								return ShowHelp( "Duplicate command line switch /NOACT" );
  106. 							}
  107. 							activatewindow = false;
  108. 							break;
  109. 						case "/NORMAL":
  110. 						case "/RESTORE":
  111. 							if ( normalwindow )
  112. 							{
  113. 								return ShowHelp( "Duplicate command line switch /NORMAL" );
  114. 							}
  115. 							if ( maximizewindow || minimizewindow )
  116. 							{
  117. 								return ShowHelp( "Invalid combination of command line switches /MAX, /MIN and/or /NORMAL" );
  118. 							}
  119. 							normalwindow = true;
  120. 							break;
  121. 						case "/SHOW":
  122. 							if ( showwindow )
  123. 							{
  124. 								return ShowHelp( "Duplicate command line switch /SHOW" );
  125. 							}
  126. 							if ( hidewindow )
  127. 							{
  128. 								return ShowHelp( "Invalid combination of command line switches /HIDE, /SHOW and/or /TRAY" );
  129. 							}
  130. 							showwindow = true;
  131. 							break;
  132. 						default:
  133. 							return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  134. 					}
  135. 				}
  136. 			}
  137.  
  138. 			showwindow = showwindow || maximizewindow || minimizewindow || normalwindow;
  139.  
  140. 			#endregion Parse Command Line
  141.  
  142.  
  143. 			if ( hidewindow )
  144. 			{
  145. 				HideConsoleWindow( );
  146. 			}
  147. 			else
  148. 			{
  149. 				ShowConsoleWindow( );
  150. 			}
  151.  
  152. 			return 0;
  153. 		}
  154.  
  155.  
  156. 		static int ShowHelp( params string[] errmsg )
  157. 		{
  158. 			// restore console visibility before showing help and/or error message
  159. 			if ( !IsWindowVisible( GetConsoleWindow( ) ) )
  160. 			{
  161. 				activatewindow = true;
  162. 				hidewindow = false;
  163. 				maximizewindow = false;
  164. 				minimizewindow = false;
  165. 				normalwindow = true;
  166. 				showwindow = true;
  167. 				ShowConsoleWindow( );
  168. 			}
  169.  
  170.  
  171. 			#region Error Message
  172.  
  173. 			if ( errmsg.Length > 0 )
  174. 			{
  175. 				List<string> errargs = new List<string>( errmsg );
  176. 				errargs.RemoveAt( 0 );
  177. 				Console.Error.WriteLine( );
  178. 				Console.ForegroundColor = ConsoleColor.Red;
  179. 				Console.Error.Write( "ERROR:\t" );
  180. 				Console.ForegroundColor = ConsoleColor.White;
  181. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  182. 				Console.ResetColor( );
  183. 			}
  184.  
  185. 			#endregion Error Message
  186.  
  187.  
  188. 			#region Help Text
  189.  
  190. 			/*
  191. 			ConsoleState.exe,  Version 2.00
  192. 			Set or get the visibility state of the current console
  193.  
  194. 			Usage:    ConsoleState.exe  [ /Hide | /Show [ options ] ]
  195.  
  196. 			Where:    /Hide         Hides the console
  197. 			          /Show         Shows the console (restores visibility)
  198.  
  199. 			Options:  /Max          Maximizes the console
  200. 			          /Min          Minimizes the console
  201. 			          /Normal       restores the console to its Normal state
  202. 			          /NoAct        do Not Activate the console window
  203.  
  204. 			Notes:    Command line switches /Max, /Min and /Normal all imply /Show.
  205. 			          Options are valid only with /Show, not with /Hide.
  206. 			          If no command line argument is used, the program will
  207. 			          check the current state and return "errorlevel" 0 if
  208. 			          visible, 1 if minimized, 2 if hidden, or -1 on errors.
  209. 			          If a command line argument is used, the program will
  210. 			          return "errorlevel" 0 if successful, or -1 on errors.
  211.  
  212. 			Credits:  Code to hide and show console by Anthony on StackOverflow.com:
  213. 			          http://stackoverflow.com/a/15079092
  214. 			          Code to check current console state by "dtb" on StackOverflow.com:
  215. 			          http://stackoverflow.com/a/2655954
  216. 			          Code to check if console is minimized Jim Tat on C# Corner:
  217. 			          https://www.c-sharpcorner.com/forums
  218. 			          /dreamincodegt-programming-helpgt-c-sharp-hi-snipercode-welcome-t
  219. 			          Console state enumeration on PInvoke.net:
  220. 			          http://www.pinvoke.net/default.aspx/Enums/ShowWindowCommand.html
  221.  
  222. 			Written by Rob van der Woude
  223. 			http://www.robvanderwoude.com
  224. 			*/
  225.  
  226. 			#endregion Help Text
  227.  
  228.  
  229. 			#region Display Help Text
  230.  
  231. 			Console.Error.WriteLine( );
  232.  
  233. 			Console.Error.WriteLine( "ConsoleState.exe,  Version {0}", progver );
  234.  
  235. 			Console.Error.WriteLine( "Set or get the visibility state of the current console" );
  236.  
  237. 			Console.Error.WriteLine( );
  238.  
  239. 			Console.Error.Write( "Usage:    " );
  240. 			Console.ForegroundColor = ConsoleColor.White;
  241. 			Console.Error.WriteLine( "ConsoleState.exe  [ /Hide | /Show [ options ] ]" );
  242. 			Console.ResetColor( );
  243.  
  244. 			Console.Error.WriteLine( );
  245.  
  246. 			Console.Error.Write( "Where:    " );
  247. 			Console.ForegroundColor = ConsoleColor.White;
  248. 			Console.Error.Write( "/Hide         H" );
  249. 			Console.ResetColor( );
  250. 			Console.Error.WriteLine( "ides the console" );
  251.  
  252. 			Console.ForegroundColor = ConsoleColor.White;
  253. 			Console.Error.Write( "          /Show         S" );
  254. 			Console.ResetColor( );
  255. 			Console.Error.WriteLine( "hows the console (restores visibility)" );
  256.  
  257. 			Console.Error.WriteLine( );
  258.  
  259. 			Console.Error.Write( "Options:  " );
  260. 			Console.ForegroundColor = ConsoleColor.White;
  261. 			Console.Error.Write( "/Max          Max" );
  262. 			Console.ResetColor( );
  263. 			Console.Error.WriteLine( "imizes the console" );
  264.  
  265. 			Console.ForegroundColor = ConsoleColor.White;
  266. 			Console.Error.Write( "          /Min          Min" );
  267. 			Console.ResetColor( );
  268. 			Console.Error.WriteLine( "imizes the console" );
  269.  
  270. 			Console.ForegroundColor = ConsoleColor.White;
  271. 			Console.Error.Write( "          /Normal" );
  272. 			Console.ResetColor( );
  273. 			Console.Error.Write( "       restores the console to its " );
  274. 			Console.ForegroundColor = ConsoleColor.White;
  275. 			Console.Error.Write( "Normal" );
  276. 			Console.ResetColor( );
  277. 			Console.Error.WriteLine( " state" );
  278.  
  279. 			Console.ForegroundColor = ConsoleColor.White;
  280. 			Console.Error.Write( "          /NoAct" );
  281. 			Console.ResetColor( );
  282. 			Console.Error.Write( "        do " );
  283. 			Console.ForegroundColor = ConsoleColor.White;
  284. 			Console.Error.Write( "No" );
  285. 			Console.ResetColor( );
  286. 			Console.Error.Write( "t" );
  287. 			Console.ForegroundColor = ConsoleColor.White;
  288. 			Console.Error.Write( "Act" );
  289. 			Console.ResetColor( );
  290. 			Console.Error.WriteLine( "ivate the console window" );
  291.  
  292. 			Console.Error.WriteLine( );
  293.  
  294. 			Console.Error.Write( "Notes:    Command line switches " );
  295. 			Console.ForegroundColor = ConsoleColor.White;
  296. 			Console.Error.Write( "/Max" );
  297. 			Console.ResetColor( );
  298. 			Console.Error.Write( ", " );
  299. 			Console.ForegroundColor = ConsoleColor.White;
  300. 			Console.Error.Write( "/Min" );
  301. 			Console.ResetColor( );
  302. 			Console.Error.Write( " and " );
  303. 			Console.ForegroundColor = ConsoleColor.White;
  304. 			Console.Error.Write( "/Normal" );
  305. 			Console.ResetColor( );
  306. 			Console.Error.Write( " all imply " );
  307. 			Console.ForegroundColor = ConsoleColor.White;
  308. 			Console.Error.Write( "/Show" );
  309. 			Console.ResetColor( );
  310. 			Console.Error.WriteLine( "." );
  311.  
  312. 			Console.Error.Write( "          Options are valid only with " );
  313. 			Console.ForegroundColor = ConsoleColor.White;
  314. 			Console.Error.Write( "/Show" );
  315. 			Console.ResetColor( );
  316. 			Console.Error.Write( ", not with " );
  317. 			Console.ForegroundColor = ConsoleColor.White;
  318. 			Console.Error.Write( "/Hide" );
  319. 			Console.ResetColor( );
  320. 			Console.Error.WriteLine( "." );
  321.  
  322. 			Console.Error.WriteLine( "          If no command line argument is used, the program will" );
  323.  
  324. 			Console.Error.WriteLine( "          check the current state and return \"errorlevel\" 0 if" );
  325.  
  326. 			Console.Error.WriteLine( "          visible, 1 if minimized, 2 if hidden, or -1 on errors." );
  327.  
  328. 			Console.Error.WriteLine( "          If a command line argument is used, the program will" );
  329.  
  330. 			Console.Error.WriteLine( "          return \"errorlevel\" 0 if successful, or -1 on errors." );
  331.  
  332. 			Console.Error.WriteLine( );
  333.  
  334. 			Console.Error.WriteLine( "Credits:  Code to hide and show console by Anthony on StackOverflow.com:" );
  335.  
  336. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  337. 			Console.Error.WriteLine( "          http://stackoverflow.com/a/15079092" );
  338. 			Console.ResetColor( );
  339.  
  340. 			Console.Error.WriteLine( "          Code to check current console state by \"dtb\" on StackOverflow.com:" );
  341.  
  342. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  343. 			Console.Error.WriteLine( "          http://stackoverflow.com/a/2655954" );
  344. 			Console.ResetColor( );
  345.  
  346. 			Console.Error.WriteLine( "          Code to check if console is minimized Jim Tat on C# Corner:" );
  347.  
  348. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  349. 			Console.Error.WriteLine( "          https://www.c-sharpcorner.com/forums" );
  350. 			Console.Error.WriteLine( "          /dreamincodegt-programming-helpgt-c-sharp-hi-snipercode-welcome-t" );
  351. 			Console.ResetColor( );
  352.  
  353. 			Console.Error.WriteLine( "          Console state enumeration on PInvoke.net:" );
  354.  
  355.  
  356. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  357. 			Console.Error.WriteLine( "          http://www.pinvoke.net/default.aspx/Enums/ShowWindowCommand.html" );
  358. 			Console.ResetColor( );
  359.  
  360. 			Console.Error.WriteLine( );
  361.  
  362. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  363.  
  364. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  365.  
  366. 			#endregion Display Help Text
  367.  
  368.  
  369. 			return -1;
  370. 		}
  371.  
  372.  
  373. 		#region Hide or Show Console
  374.  
  375. 		// Source: http://stackoverflow.com/a/15079092
  376. 		public static void ShowConsoleWindow( )
  377. 		{
  378. 			var handle = GetConsoleWindow( );
  379. 			if ( handle == IntPtr.Zero )
  380. 			{
  381. 				AllocConsole( );
  382. 			}
  383. 			else
  384. 			{
  385. 				if ( maximizewindow )
  386. 				{
  387. 					ShowWindow( handle, (int) ShowWindowCommands.ShowMaximized );
  388. 				}
  389. 				else if ( minimizewindow )
  390. 				{
  391. 					if ( activatewindow )
  392. 					{
  393. 						ShowWindow( handle, (int) ShowWindowCommands.ShowMinimized );
  394. 					}
  395. 					else
  396. 					{
  397. 						ShowWindow( handle, (int) ShowWindowCommands.ShowMinNoActive );
  398. 					}
  399. 				}
  400. 				else
  401. 				{
  402. 					ShowWindow( handle, (int) ShowWindowCommands.Show );
  403. 					if ( activatewindow )
  404. 					{
  405. 						ShowWindow( handle, (int) ShowWindowCommands.Restore ); // Restore window size and position
  406. 					}
  407. 				}
  408. 			}
  409. 			if ( debugmode )
  410. 			{
  411. 				Console.Error.WriteLine( "Command Line    = {0}", Environment.CommandLine );
  412. 				Console.Error.WriteLine( "activatewindow  = {0}", activatewindow );
  413. 				Console.Error.WriteLine( "hidewindow      = {0}", hidewindow );
  414. 				Console.Error.WriteLine( "maximizewindow  = {0}", maximizewindow );
  415. 				Console.Error.WriteLine( "minimizewindow  = {0}", minimizewindow );
  416. 				Console.Error.WriteLine( "normalwindow    = {0}", normalwindow );
  417. 				Console.Error.WriteLine( "showwindow      = {0}", showwindow );
  418. 				Console.Error.WriteLine( "IsIconic        = {0}", IsIconic( handle ) );
  419. 				Console.Error.WriteLine( "IsWindowVisible = {0}", IsWindowVisible( handle ) );
  420. 				Console.Error.WriteLine( );
  421. 			}
  422. 		}
  423.  
  424.  
  425. 		// Source: http://stackoverflow.com/a/15079092
  426. 		public static void HideConsoleWindow( )
  427. 		{
  428. 			var handle = GetConsoleWindow( );
  429. 			ShowWindow( handle, (int) ShowWindowCommands.Hide );
  430. 			if ( debugmode )
  431. 			{
  432. 				Console.Error.WriteLine( "Command Line    = {0}", Environment.CommandLine );
  433. 				Console.Error.WriteLine( "activatewindow  = {0}", activatewindow );
  434. 				Console.Error.WriteLine( "hidewindow      = {0}", hidewindow );
  435. 				Console.Error.WriteLine( "maximizewindow  = {0}", maximizewindow );
  436. 				Console.Error.WriteLine( "minimizewindow  = {0}", minimizewindow );
  437. 				Console.Error.WriteLine( "normalwindow    = {0}", normalwindow );
  438. 				Console.Error.WriteLine( "showwindow      = {0}", showwindow );
  439. 				Console.Error.WriteLine( "IsIconic        = {0}", IsIconic( handle ) );
  440. 				Console.Error.WriteLine( "IsWindowVisible = {0}", IsWindowVisible( handle ) );
  441. 				Console.Error.WriteLine( );
  442. 			}
  443. 		}
  444.  
  445.  
  446. 		// Source: http://stackoverflow.com/a/15079092
  447. 		[DllImport( "kernel32.dll", SetLastError = true )]
  448. 		static extern bool AllocConsole( );
  449.  
  450.  
  451. 		// Source: http://stackoverflow.com/a/15079092
  452. 		[DllImport( "kernel32.dll" )]
  453. 		static extern IntPtr GetConsoleWindow( );
  454.  
  455.  
  456. 		// Source: http://stackoverflow.com/a/15079092
  457. 		[DllImport( "user32.dll" )]
  458. 		static extern bool ShowWindow( IntPtr hWnd, int nCmdShow );
  459.  
  460.  
  461. 		// Source: http://stackoverflow.com/a/2655954
  462. 		[DllImport( "user32.dll" )]
  463. 		[return: MarshalAs( UnmanagedType.Bool )]
  464. 		static extern bool IsWindowVisible( IntPtr hWnd );
  465.  
  466.  
  467. 		[DllImport( "user32.dll" )]
  468. 		[return: MarshalAs( UnmanagedType.Bool )]
  469. 		static extern bool IsIconic( IntPtr hWnd );
  470.  
  471. 		#endregion Hide or Show Console
  472. 	}
  473.  
  474.  
  475. 	public enum ShowWindowCommands
  476. 	{
  477. 		// Source: http://www.pinvoke.net/default.aspx/Enums/ShowWindowCommand.html
  478.  
  479. 		/// <summary>
  480. 		/// Hides the window and activates another window.
  481. 		/// </summary>
  482. 		Hide = 0,
  483.  
  484. 		/// <summary>
  485. 		/// Activates and displays a window. If the window is minimized or
  486. 		/// maximized, the system restores it to its original size and position.
  487. 		/// An application should specify this flag when displaying the window
  488. 		/// for the first time.
  489. 		/// </summary>
  490. 		Normal = 1,
  491.  
  492. 		/// <summary>
  493. 		/// Activates the window and displays it as a minimized window.
  494. 		/// </summary>
  495. 		ShowMinimized = 2,
  496.  
  497. 		/// <summary>
  498. 		/// Maximizes the specified window.
  499. 		/// </summary>
  500. 		Maximize = 3,
  501.  
  502. 		/// <summary>
  503. 		/// Activates the window and displays it as a maximized window.
  504. 		/// </summary>      
  505. 		ShowMaximized = 3,
  506.  
  507. 		/// <summary>
  508. 		/// Displays a window in its most recent size and position. This value
  509. 		/// is similar to <see cref="Win32.ShowWindowCommand.Normal"/>, except
  510. 		/// the window is not activated.
  511. 		/// </summary>
  512. 		ShowNoActivate = 4,
  513.  
  514. 		/// <summary>
  515. 		/// Activates the window and displays it in its current size and position.
  516. 		/// </summary>
  517. 		Show = 5,
  518.  
  519. 		/// <summary>
  520. 		/// Minimizes the specified window and activates the next top-level
  521. 		/// window in the Z order.
  522. 		/// </summary>
  523. 		Minimize = 6,
  524.  
  525. 		/// <summary>
  526. 		/// Displays the window as a minimized window. This value is similar to
  527. 		/// <see cref="Win32.ShowWindowCommand.ShowMinimized"/>, except the
  528. 		/// window is not activated.
  529. 		/// </summary>
  530. 		ShowMinNoActive = 7,
  531.  
  532. 		/// <summary>
  533. 		/// Displays the window in its current size and position. This value is
  534. 		/// similar to <see cref="Win32.ShowWindowCommand.Show"/>, except the
  535. 		/// window is not activated.
  536. 		/// </summary>
  537. 		ShowNA = 8,
  538.  
  539. 		/// <summary>
  540. 		/// Activates and displays the window. If the window is minimized or
  541. 		/// maximized, the system restores it to its original size and position.
  542. 		/// An application should specify this flag when restoring a minimized window.
  543. 		/// </summary>
  544. 		Restore = 9,
  545.  
  546. 		/// <summary>
  547. 		/// Sets the show state based on the SW_* value specified in the
  548. 		/// STARTUPINFO structure passed to the CreateProcess function by the
  549. 		/// program that started the application.
  550. 		/// </summary>
  551. 		ShowDefault = 10,
  552.  
  553. 		/// <summary>
  554. 		///  <b>Windows 2000/XP:</b> Minimizes a window, even if the thread
  555. 		/// that owns the window is not responding. This flag should only be
  556. 		/// used when minimizing windows from a different thread.
  557. 		/// </summary>
  558. 		ForceMinimize = 11
  559. 	}
  560. }
  561.  

page last uploaded: 2018-12-04, 10:47