Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for inputbox.cs

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Timers;
  9. using System.Windows.Forms;
  10.  
  11.  
  12. namespace RobvanderWoude
  13. {
  14. 	class InputBox
  15. 	{
  16. 		public const string progver = "1.33";
  17.  
  18. 		#region Global Variables
  19.  
  20. 		public const int defheight = 110;
  21. 		public const int deftimeout = 60;
  22. 		public const int defwidth = 200;
  23. 		public static ConsoleColor bold = ConsoleColor.White;
  24. 		public static MaskedTextBox maskedTextBox;
  25. 		public static TextBox textBox;
  26. 		public static bool ASCIIonly = false;
  27. 		public static bool bw = false;
  28. 		public static bool filtered = true;
  29. 		public static bool oddrow = false;
  30. 		public static bool password = false;
  31. 		public static bool timeoutelapsed = false;
  32. 		public static bool usemask = false;
  33. 		public static bool regexset = false;
  34. 		public static string defanswer = "Default answer";
  35. 		public static string pattern = ".*";
  36.  
  37. 		#endregion Global Variables
  38.  
  39.  
  40. 		[STAThread]
  41. 		static int Main( string[] args )
  42. 		{
  43. 			// Based on code by Gorkem Gencay on StackOverflow.com:
  44. 			// http://stackoverflow.com/questions/97097/what-is-the-c-sharp-version-of-vb-nets-inputdialog#17546909
  45.  
  46. 			#region Initialize variables
  47.  
  48. 			const string deftitle = "Title";
  49. 			const string deftext = "Prompt";
  50.  
  51. 			bool heightset = false;
  52. 			bool showpassword = false;
  53. 			bool timeoutset = false;
  54. 			bool widthset = false;
  55. 			string input = string.Empty;
  56. 			string mask = String.Empty;
  57. 			string showpasswordprompt = "Show password";
  58. 			string text = deftext;
  59. 			string title = deftitle;
  60. 			int height = defheight;
  61. 			int timeout = 0;
  62. 			int width = defwidth;
  63. 			string cancelcaption = "&Cancel";
  64. 			string okcaption = "&OK";
  65. 			string localizationstring = String.Empty;
  66. 			bool localizedcaptionset = false;
  67.  
  68. 			#endregion Initialize variables
  69.  
  70.  
  71. 			#region Command Line Parsing
  72.  
  73. 			if ( args.Length == 0 )
  74. 			{
  75. 				return ErrorMessage( );
  76. 			}
  77.  
  78. 			foreach ( string arg in args )
  79. 			{
  80. 				if ( arg == "/?" )
  81. 				{
  82. 					return ErrorMessage( );
  83. 				}
  84. 			}
  85.  
  86. 			text = String.Empty;
  87. 			title = String.Empty;
  88. 			defanswer = String.Empty;
  89.  
  90. 			foreach ( string arg in args )
  91. 			{
  92. 				if ( arg[0] == '/' )
  93. 				{
  94. 					if ( arg.Length == 1 )
  95. 					{
  96. 						return ErrorMessage( );
  97. 					}
  98. 					else if ( arg.Length == 2 )
  99. 					{
  100. 						switch ( arg.ToString( ).ToUpper( ) )
  101. 						{
  102. 							case "/A":
  103. 								if ( ASCIIonly )
  104. 								{
  105. 									return ErrorMessage( "Duplicate command line switch /A" );
  106. 								}
  107. 								ASCIIonly = true;
  108. 								break;
  109. 							case "/B":
  110. 								if ( bw )
  111. 								{
  112. 									return ErrorMessage( "Duplicate command line switch /B" );
  113. 								}
  114. 								bw = true;
  115. 								bold = Console.ForegroundColor;
  116. 								break;
  117. 							case "/L":
  118. 								if ( localizedcaptionset )
  119. 								{
  120. 									return ErrorMessage( "Duplicate command line switch /L" );
  121. 								}
  122. 								localizedcaptionset = true;
  123. 								break;
  124. 							case "/M":
  125. 								return HelpMessage( "mask" );
  126. 							case "/N":
  127. 								if ( !filtered )
  128. 								{
  129. 									return ErrorMessage( "Duplicate command line switch /N" );
  130. 								}
  131. 								filtered = false;
  132. 								break;
  133. 							case "/P":
  134. 								if ( password )
  135. 								{
  136. 									return ErrorMessage( "Duplicate command line switch /P" );
  137. 								}
  138. 								password = true;
  139. 								break;
  140. 							case "/S":
  141. 								if ( showpassword )
  142. 								{
  143. 									return ErrorMessage( "Duplicate command line switch /S" );
  144. 								}
  145. 								showpassword = true;
  146. 								break;
  147. 							case "/T":
  148. 								if ( timeoutset )
  149. 								{
  150. 									return ErrorMessage( "Duplicate command line switch /T" );
  151. 								}
  152. 								timeout = deftimeout;
  153. 								timeoutset = true;
  154. 								break;
  155. 							default:
  156. 								return ErrorMessage( "Invalid command line switch {0}", arg );
  157. 						}
  158. 					}
  159. 					else if ( arg.Length == 3 )
  160. 					{
  161. 						switch ( arg.ToUpper( ) )
  162. 						{
  163. 							case "/M:":
  164. 								ErrorMessage( "No mask specified with /M" );
  165. 								Console.WriteLine( "\n\n" );
  166. 								return HelpMessage( "mask" );
  167. 							default:
  168. 								return ErrorMessage( "Invalid command line switch \"{0}\"", arg.ToUpper( ) );
  169. 						}
  170. 					}
  171. 					else
  172. 					{
  173. 						switch ( arg.Substring( 0, 3 ).ToUpper( ) )
  174. 						{
  175. 							case "/H:":
  176. 								if ( heightset )
  177. 								{
  178. 									return ErrorMessage( "Duplicate command line switch /H" );
  179. 								}
  180. 								try
  181. 								{
  182. 									height = Convert.ToInt32( arg.Substring( 3 ) );
  183. 									if ( height < defheight || height > Screen.PrimaryScreen.Bounds.Height )
  184. 									{
  185. 										return ErrorMessage( "Invalid screen height: \"{0}\"\n\tHeight must be an integer between {1} and {2} (screen height)", arg.Substring( 3 ), defheight.ToString( ), Screen.PrimaryScreen.Bounds.Height.ToString( ) );
  186. 									}
  187. 									heightset = true;
  188. 								}
  189. 								catch ( FormatException e )
  190. 								{
  191. 									return ErrorMessage( "Invalid height: \"{0}\"\n\t{1}", arg.Substring( 3 ), e.Message );
  192. 								}
  193. 								break;
  194. 							case "/L:":
  195. 								if ( localizedcaptionset )
  196. 								{
  197. 									return ErrorMessage( "Duplicate command line switch /L" );
  198. 								}
  199. 								localizedcaptionset = true;
  200. 								localizationstring = arg.Substring( 3 );
  201. 								break;
  202. 							case "/M:":
  203. 								if ( usemask )
  204. 								{
  205. 									return ErrorMessage( "Duplicate command line switch /M" );
  206. 								}
  207. 								mask = arg.Substring( 3 ).Trim( "\"".ToCharArray( ) );
  208. 								if ( String.IsNullOrWhiteSpace( mask ) )
  209. 								{
  210. 									ErrorMessage( "No mask specified with /M" );
  211. 									Console.WriteLine( "\n\n" );
  212. 									return HelpMessage( "mask" );
  213. 								}
  214. 								usemask = true;
  215. 								break;
  216. 							case "/R:":
  217. 								if ( regexset )
  218. 								{
  219. 									return ErrorMessage( "Duplicate command line switch /R" );
  220. 								}
  221. 								pattern = arg.Substring( 3 );
  222. 								regexset = true;
  223. 								break;
  224. 							case "/S:":
  225. 								if ( showpassword )
  226. 								{
  227. 									return ErrorMessage( "Duplicate command line switch /S" );
  228. 								}
  229. 								showpassword = true;
  230. 								showpasswordprompt = arg.Substring( 3 );
  231. 								break;
  232. 							case "/T:":
  233. 								if ( timeoutset )
  234. 								{
  235. 									return ErrorMessage( "Duplicate command line switch /T" );
  236. 								}
  237. 								try
  238. 								{
  239. 									timeout = Convert.ToInt32( arg.Substring( 3 ) ) * 1000;
  240. 									if ( timeout < 1000 )
  241. 									{
  242. 										return ErrorMessage( "Invalid timeout: \"{0}\"\n\tTimeout value must be a positive integer, at least 1.", arg.Substring( 3 ) );
  243. 									}
  244. 									timeoutset = true;
  245. 								}
  246. 								catch ( FormatException e )
  247. 								{
  248. 									return ErrorMessage( "Invalid timeout: \"{0}\"\n\t{1}", arg.Substring( 3 ), e.Message );
  249. 								}
  250. 								break;
  251. 							case "/W:":
  252. 								if ( widthset )
  253. 								{
  254. 									return ErrorMessage( "Duplicate command line switch /W" );
  255. 								}
  256. 								try
  257. 								{
  258. 									width = Convert.ToInt32( arg.Substring( 3 ) );
  259. 									if ( width < defwidth || width > Screen.PrimaryScreen.Bounds.Width )
  260. 									{
  261. 										return ErrorMessage( "Invalid screen width: \"{0}\"\n\tWidth must be an integer between {1} and {2} (screen width)", arg.Substring( 3 ), defwidth.ToString( ), Screen.PrimaryScreen.Bounds.Width.ToString( ) );
  262. 									}
  263. 									widthset = true;
  264. 								}
  265. 								catch ( FormatException e )
  266. 								{
  267. 									return ErrorMessage( "Invalid width: \"{0}\"\n\t{1}", arg.Substring( 3 ), e.Message );
  268. 								}
  269. 								break;
  270. 							default:
  271. 								return ErrorMessage( "Invalid command line switch \"{0}\"", arg );
  272. 						}
  273. 					}
  274. 				}
  275. 				else
  276. 				{
  277. 					if ( String.IsNullOrWhiteSpace( text ) )
  278. 					{
  279. 						text = arg;
  280. 					}
  281. 					else if ( String.IsNullOrWhiteSpace( title ) )
  282. 					{
  283. 						title = arg;
  284. 					}
  285. 					else if ( String.IsNullOrWhiteSpace( defanswer ) )
  286. 					{
  287. 						defanswer = arg;
  288. 					}
  289. 					else
  290. 					{
  291. 						return ErrorMessage( "Invalid command line argument \"{0}\"", arg );
  292. 					}
  293. 				}
  294. 			}
  295.  
  296. 			// Default title if none specified
  297. 			if ( String.IsNullOrWhiteSpace( title ) )
  298. 			{
  299. 				title = "? 2014 Rob van der Woude";
  300. 			}
  301.  
  302. 			// "Bold" color depends on /BW
  303. 			if ( bw )
  304. 			{
  305. 				bold = Console.ForegroundColor;
  306. 			}
  307. 			else
  308. 			{
  309. 				bold = ConsoleColor.White;
  310. 			}
  311.  
  312. 			// Switch /A requires /M
  313. 			if ( ASCIIonly && !usemask )
  314. 			{
  315. 				return ErrorMessage( "Command line switch /A (ASCII only) can only be used together with /M" );
  316. 			}
  317.  
  318. 			// Switch /S implies /P
  319. 			if ( showpassword )
  320. 			{
  321. 				password = true;
  322. 			}
  323.  
  324. 			// Set timer if /T:timeout was specified
  325. 			if ( timeoutset )
  326. 			{
  327. 				System.Timers.Timer timer = new System.Timers.Timer( );
  328. 				timer.Elapsed += new ElapsedEventHandler( timer_Elapsed );
  329. 				timer.Interval = timeout;
  330. 				timer.Start( );
  331. 			}
  332.  
  333. 			// For /S (Show password checkbox) add 25 px to window height unless height is specified
  334. 			if ( showpassword && !heightset )
  335. 			{
  336. 				height += 25;
  337. 			}
  338.  
  339. 			#endregion Command Line Parsing
  340.  
  341.  
  342. 			#region Set Localized Captions
  343.  
  344. 			if ( localizedcaptionset )
  345. 			{
  346. 				cancelcaption = Load( "user32.dll", 801, cancelcaption );
  347. 				okcaption = Load( "user32.dll", 800, okcaption );
  348. 				if ( !String.IsNullOrWhiteSpace( localizationstring ) )
  349. 				{
  350. 					string pattern = @"^((OK|Cancel)=[^;\""]*;)*((OK|Cancel)=[^;\""]*);?$";
  351. 					Regex regex = new Regex( pattern, RegexOptions.IgnoreCase );
  352. 					if ( regex.IsMatch( localizationstring ) )
  353. 					{
  354. 						string[] locstrings = localizationstring.Split( ";".ToCharArray( ) );
  355. 						foreach ( string locstring in locstrings )
  356. 						{
  357. 							string key = locstring.Substring( 0, locstring.IndexOf( '=' ) );
  358. 							string val = locstring.Substring( Math.Min( locstring.IndexOf( '=' ) + 1, locstring.Length - 1 ) );
  359. 							if ( !String.IsNullOrWhiteSpace( val ) )
  360. 							{
  361. 								switch ( key.ToUpper( ) )
  362. 								{
  363. 									case "OK":
  364. 										okcaption = val;
  365. 										break;
  366. 									case "CANCEL":
  367. 										cancelcaption = val;
  368. 										break;
  369. 									default:
  370. 										return ErrorMessage( "Invalid localization key \"{0}\"", key );
  371. 								}
  372. 							}
  373. 						}
  374. 					}
  375. 					else
  376. 					{
  377. 						return ErrorMessage( "Invalid localization string:\n\t{0}", localizationstring );
  378. 					}
  379. 				}
  380. 			}
  381.  
  382. 			#endregion Set Localized Captions
  383.  
  384.  
  385. 			#region Define Form
  386.  
  387. 			Size size = new Size( width, height );
  388. 			Form inputBox = new Form( );
  389.  
  390. 			inputBox.FormBorderStyle = FormBorderStyle.FixedDialog;
  391. 			inputBox.MaximizeBox = false;
  392. 			inputBox.MinimizeBox = false;
  393. 			inputBox.StartPosition = FormStartPosition.CenterParent;
  394. 			inputBox.ClientSize = size;
  395. 			inputBox.Text = title;
  396.  
  397. 			Label labelPrompt = new Label( );
  398. 			labelPrompt.Size = new Size( width - 20, height - 90 );
  399. 			labelPrompt.Location = new Point( 10, 10 );
  400. 			labelPrompt.Text = text.Replace( "\\n", "\n" );
  401. 			inputBox.Controls.Add( labelPrompt );
  402.  
  403. 			textBox = new TextBox( );
  404. 			textBox.Size = new Size( width - 20, 25 );
  405. 			if ( showpassword )
  406. 			{
  407. 				textBox.Location = new Point( 10, height - 100 );
  408. 			}
  409. 			else
  410. 			{
  411. 				textBox.Location = new Point( 10, height - 75 );
  412. 			}
  413. 			if ( password )
  414. 			{
  415. 				textBox.PasswordChar = '*';
  416. 				if ( showpassword )
  417. 				{
  418. 					// Insert a checkbox with label "Show password" 25 px below the textbox
  419. 					CheckBox checkbox = new CheckBox( );
  420. 					checkbox.Checked = false;
  421. 					checkbox.Location = new Point( 11, textBox.Location.Y + 25 );
  422. 					checkbox.Width = inputBox.Width - 22;
  423. 					checkbox.Click += new EventHandler( checkbox_Click );
  424. 					checkbox.Text = showpasswordprompt;
  425. 					inputBox.Controls.Add( checkbox );
  426. 				}
  427. 			}
  428. 			else
  429. 			{
  430. 				textBox.Text = defanswer;
  431. 			}
  432.  
  433. 			maskedTextBox = new MaskedTextBox( );
  434. 			maskedTextBox.Mask = mask;
  435. 			maskedTextBox.Location = textBox.Location;
  436. 			maskedTextBox.PasswordChar = textBox.PasswordChar;
  437. 			maskedTextBox.Text = textBox.Text;
  438. 			maskedTextBox.Size = textBox.Size;
  439. 			maskedTextBox.AsciiOnly = ASCIIonly;
  440.  
  441. 			if ( usemask )
  442. 			{
  443. 				inputBox.Controls.Add( maskedTextBox );
  444. 			}
  445. 			else
  446. 			{
  447. 				inputBox.Controls.Add( textBox );
  448. 			}
  449.  
  450. 			Button okButton = new Button( );
  451. 			okButton.DialogResult = DialogResult.OK;
  452. 			okButton.Name = "okButton";
  453. 			okButton.Size = new Size( 80, 25 );
  454. 			okButton.Text = okcaption;
  455. 			okButton.Location = new Point( width / 2 - 10 - 80, height - 40 );
  456. 			inputBox.Controls.Add( okButton );
  457.  
  458. 			Button cancelButton = new Button( );
  459. 			cancelButton.DialogResult = DialogResult.Cancel;
  460. 			cancelButton.Name = "cancelButton";
  461. 			cancelButton.Size = new Size( 80, 25 );
  462. 			cancelButton.Text = cancelcaption;
  463. 			cancelButton.Location = new Point( width / 2 + 10, height - 40 );
  464. 			inputBox.Controls.Add( cancelButton );
  465.  
  466. 			inputBox.AcceptButton = okButton;  // OK on Enter
  467. 			inputBox.CancelButton = cancelButton; // Cancel on Esc
  468. 			inputBox.Activate( );
  469. 			inputBox.BringToFront( );
  470. 			inputBox.Focus( );
  471.  
  472. 			if ( usemask )
  473. 			{
  474. 				maskedTextBox.BringToFront( ); // Bug workaround
  475. 				maskedTextBox.Select( 0, 0 ); // Move cursor to begin
  476. 				maskedTextBox.Focus( );
  477. 			}
  478. 			else
  479. 			{
  480. 				textBox.BringToFront( ); // Bug workaround
  481. 				textBox.Select( 0, 0 ); // Move cursor to begin
  482. 				textBox.Focus( );
  483. 			}
  484.  
  485. 			#endregion Define Form
  486.  
  487.  
  488. 			#region Show Dialog and Return Result
  489.  
  490. 			DialogResult result = inputBox.ShowDialog( );
  491. 			if ( result == DialogResult.OK )
  492. 			{
  493. 				int rc = ValidateAndShowResult( );
  494. 				return rc;
  495. 			}
  496. 			else
  497. 			{
  498. 				if ( timeoutelapsed )
  499. 				{
  500. 					ValidateAndShowResult( );
  501. 					return 3;
  502. 				}
  503. 				else
  504. 				{
  505. 					return 2;
  506. 				}
  507. 			}
  508.  
  509. 			#endregion Show Dialog and Return Result
  510. 		}
  511.  
  512.  
  513. 		#region Event Handlers
  514.  
  515. 		public static void checkbox_Click( object sender, System.EventArgs e )
  516. 		{
  517. 			// Toggle between hidden and normal text
  518. 			if ( usemask )
  519. 			{
  520. 				if ( maskedTextBox.PasswordChar == '*' )
  521. 				{
  522. 					maskedTextBox.PasswordChar = '\0';
  523. 				}
  524. 				else
  525. 				{
  526. 					maskedTextBox.PasswordChar = '*';
  527. 				}
  528. 			}
  529. 			else
  530. 			{
  531. 				if ( textBox.PasswordChar == '*' )
  532. 				{
  533. 					textBox.PasswordChar = '\0';
  534. 				}
  535. 				else
  536. 				{
  537. 					textBox.PasswordChar = '*';
  538. 				}
  539. 			}
  540. 		}
  541.  
  542.  
  543. 		public static void timer_Elapsed( object sender, System.EventArgs e )
  544. 		{
  545. 			timeoutelapsed = true;
  546. 			Process.GetCurrentProcess( ).CloseMainWindow( );
  547. 		}
  548.  
  549. 		#endregion Event Handlers
  550.  
  551.  
  552. 		public static int ErrorMessage( params string[] errmsg )
  553. 		{
  554. 			/*
  555. 			InputBox,  Version 1.33
  556. 			Prompt for input (GUI)
  557.  
  558. 			Usage:   INPUTBOX  [ "prompt"  [ "title"  [ "default" ] ] ] [ options ]
  559.  
  560. 			Where:   "prompt"    is the text above the input field (use \n for new line)
  561. 			         "title"     is the caption in the title bar
  562. 			         "default"   is the default answer shown in the input field
  563.  
  564. 			Options: /A          accepts ASCII characters only (requires /M)
  565. 			         /B          use standard Black and white in console, no highlighting
  566. 			         /H:height   sets the Height of the input box
  567. 			                     (default: 110; minimum: 110; maximum: screen height)
  568.                      /L[:string] use Localized or custom captions (see Notes)
  569. 			         /M:mask     accept input only if it matches mask (template)
  570. 			         /N          Not filtered, only doublequotes are removed from input
  571. 			                     (default: remove & < > | ")
  572. 			         /P          hides (masks) the input text (for Passwords)
  573. 			         /R:regex    accept input only if it matches Regular expression regex
  574. 			         /S[:text]   inserts a checkbox "Show password" (or specified text)
  575. 			         /T[:sec]    sets the optional Timeout in seconds (default: 60)
  576. 			         /W:width    sets the Width of the input box
  577. 			                     (default: 200; minimum: 200; maximum: screen width)
  578.  
  579. 			Example: prompt for password
  580. 			InputBox.exe "Enter your password:" "Login" /S
  581.  
  582. 			Example: fixed length hexadecimal input (enter as a single command line)
  583. 			InputBox.exe "Enter a MAC address:" "MAC Address" "0022446688AA"
  584. 			             /M:">CC\:CC\:CC\:CC\:CC\:CC" /R:"[0-9A-F]{2}(\:[0-9A-F]{2}){5}"
  585.  
  586. 			Notes:   For hidden input (/P and/or /S), "default" will be ignored.
  587. 			         Be careful with /N, use doublequotes for the "captured" result,
  588. 			         or redirect the result to a (temporary) file.
  589. 			         Show password (/S) implies hiding the input text (/P).
  590. 			         Use /M (without mask) to show detailed help on the mask language.
  591. 			         Use /L for Localized "OK" and "Cancel" button captions.
  592. 			         Custom captions require a string like /L:"OK=caption;Cancel=caption"
  593. 			         (button=caption pairs separated by semicolons, each button optional).
  594. 			         Text from input is written to Standard Out only if "OK" is clicked.
  595. 			         Return code is 0 for "OK", 1 for (command line) errors, 2 for
  596. 			         "Cancel", 3 on timeout, 4 if no regex or mask match.
  597.  
  598. 			Credits: On-the-fly form based on code by Gorkem Gencay on StackOverflow:
  599. 			         http://stackoverflow.com/questions/97097#17546909
  600. 			         Code to retrieve localized button captions by Martin Stoeckli:
  601. 			         http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources
  602.  
  603. 			Written by Rob van der Woude
  604. 			http://www.robvanderwoude.com
  605. 			*/
  606.  
  607. 			if ( errmsg.Length > 0 )
  608. 			{
  609. 				List<string> errargs = new List<string>( errmsg );
  610. 				errargs.RemoveAt( 0 );
  611. 				Console.Error.WriteLine( );
  612. 				if ( !bw )
  613. 				{
  614. 					Console.ForegroundColor = ConsoleColor.Red;
  615. 				}
  616. 				Console.Error.Write( "ERROR:\t" );
  617. 				Console.ForegroundColor = bold;
  618. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  619. 				Console.ResetColor( );
  620. 			}
  621.  
  622. 			Console.Error.WriteLine( );
  623.  
  624. 			Console.Error.WriteLine( "InputBox,  Version {0}", progver );
  625.  
  626. 			Console.Error.WriteLine( "Prompt for input (GUI)" );
  627.  
  628. 			Console.Error.WriteLine( );
  629.  
  630. 			Console.Error.Write( "Usage:   " );
  631. 			Console.ForegroundColor = bold;
  632. 			Console.Error.WriteLine( "INPUTBOX  [ \"prompt\"  [ \"title\"  [ \"default\" ] ] ] [ options ]" );
  633. 			Console.ResetColor( );
  634.  
  635. 			Console.Error.WriteLine( );
  636.  
  637. 			Console.Error.Write( "Where:   " );
  638. 			Console.ForegroundColor = bold;
  639. 			Console.Error.Write( "\"prompt\"" );
  640. 			Console.ResetColor( );
  641. 			Console.Error.WriteLine( "    is the text above the input field (use \\n for new line)" );
  642.  
  643. 			Console.ForegroundColor = bold;
  644. 			Console.Error.Write( "         \"title\"" );
  645. 			Console.ResetColor( );
  646. 			Console.Error.WriteLine( "     is the caption in the title bar" );
  647.  
  648. 			Console.ForegroundColor = bold;
  649. 			Console.Error.Write( "         \"default\"" );
  650. 			Console.ResetColor( );
  651. 			Console.Error.WriteLine( "   is the default answer shown in the input field" );
  652.  
  653. 			Console.Error.WriteLine( );
  654.  
  655. 			Console.Error.Write( "Options: " );
  656. 			Console.ForegroundColor = bold;
  657. 			Console.Error.Write( "/A" );
  658. 			Console.ResetColor( );
  659. 			Console.Error.Write( "          accepts " );
  660. 			Console.ForegroundColor = bold;
  661. 			Console.Error.Write( "A" );
  662. 			Console.ResetColor( );
  663. 			Console.Error.Write( "SCII characters only (requires " );
  664. 			Console.ForegroundColor = bold;
  665. 			Console.Error.Write( "/M" );
  666. 			Console.ResetColor( );
  667. 			Console.Error.WriteLine( ")" );
  668.  
  669. 			Console.ForegroundColor = bold;
  670. 			Console.Error.Write( "         /B" );
  671. 			Console.ResetColor( );
  672. 			Console.Error.Write( "          use standard " );
  673. 			Console.ForegroundColor = bold;
  674. 			Console.Error.Write( "B" );
  675. 			Console.ResetColor( );
  676. 			Console.Error.WriteLine( "lack and white in console, no highlighting" );
  677.  
  678. 			Console.ForegroundColor = bold;
  679. 			Console.Error.Write( "         /H:height" );
  680. 			Console.ResetColor( );
  681. 			Console.Error.Write( "   sets the " );
  682. 			Console.ForegroundColor = bold;
  683. 			Console.Error.Write( "H" );
  684. 			Console.ResetColor( );
  685. 			Console.Error.WriteLine( "eight of the input box" );
  686.  
  687. 			Console.Error.WriteLine( "                     (default: {0}; minimum: {0}; maximum: screen height)", defheight );
  688.  
  689. 			Console.ForegroundColor = bold;
  690. 			Console.Error.Write( "         /L[:string]" );
  691. 			Console.ResetColor( );
  692. 			Console.Error.Write( " use " );
  693. 			Console.ForegroundColor = bold;
  694. 			Console.Error.Write( "L" );
  695. 			Console.ResetColor( );
  696. 			Console.Error.WriteLine( "ocalized or custom captions (see Notes)" );
  697.  
  698. 			Console.ForegroundColor = bold;
  699. 			Console.Error.Write( "         /M:mask" );
  700. 			Console.ResetColor( );
  701. 			Console.Error.Write( "     accept input only if it matches " );
  702. 			Console.ForegroundColor = bold;
  703. 			Console.Error.WriteLine( "mask" );
  704. 			Console.ResetColor( );
  705.  
  706. 			Console.ForegroundColor = bold;
  707. 			Console.Error.Write( "         /N          N" );
  708. 			Console.ResetColor( );
  709. 			Console.Error.WriteLine( "ot filtered, only doublequotes are removed from input" );
  710.  
  711. 			Console.Error.Write( "                     (default: remove " );
  712. 			Console.ForegroundColor = bold;
  713. 			Console.Error.Write( "& < > | \"" );
  714. 			Console.ResetColor( );
  715. 			Console.Error.WriteLine( ")" );
  716.  
  717. 			Console.ForegroundColor = bold;
  718. 			Console.Error.Write( "         /P" );
  719. 			Console.ResetColor( );
  720. 			Console.Error.Write( "          hides (masks) the input text (for " );
  721. 			Console.ForegroundColor = bold;
  722. 			Console.Error.Write( "P" );
  723. 			Console.ResetColor( );
  724. 			Console.Error.WriteLine( "asswords)" );
  725.  
  726. 			Console.ForegroundColor = bold;
  727. 			Console.Error.Write( "         /R:regex" );
  728. 			Console.ResetColor( );
  729. 			Console.Error.Write( "    accept input only if it matches " );
  730. 			Console.ForegroundColor = bold;
  731. 			Console.Error.Write( "R" );
  732. 			Console.ResetColor( );
  733. 			Console.Error.Write( "egular expression " );
  734. 			Console.ForegroundColor = bold;
  735. 			Console.Error.WriteLine( "regex" );
  736. 			Console.ResetColor( );
  737.  
  738. 			Console.ForegroundColor = bold;
  739. 			Console.Error.Write( "         /S[:text]" );
  740. 			Console.ResetColor( );
  741. 			Console.Error.Write( "   inserts a checkbox \"" );
  742. 			Console.ForegroundColor = bold;
  743. 			Console.Error.Write( "S" );
  744. 			Console.ResetColor( );
  745. 			Console.Error.Write( "how password\" (or specified " );
  746. 			Console.ForegroundColor = bold;
  747. 			Console.Error.Write( "text" );
  748. 			Console.ResetColor( );
  749. 			Console.Error.WriteLine( ")" );
  750.  
  751. 			Console.ForegroundColor = bold;
  752. 			Console.Error.Write( "         /T[:sec]" );
  753. 			Console.ResetColor( );
  754. 			Console.Error.Write( "    sets the optional " );
  755. 			Console.ForegroundColor = bold;
  756. 			Console.Error.Write( "T" );
  757. 			Console.ResetColor( );
  758. 			Console.Error.Write( "imeout in " );
  759. 			Console.ForegroundColor = bold;
  760. 			Console.Error.Write( "sec" );
  761. 			Console.ResetColor( );
  762. 			Console.Error.WriteLine( "onds (default: {0})", deftimeout );
  763.  
  764. 			Console.ForegroundColor = bold;
  765. 			Console.Error.Write( "         /W:width" );
  766. 			Console.ResetColor( );
  767. 			Console.Error.Write( "    sets the " );
  768. 			Console.ForegroundColor = bold;
  769. 			Console.Error.Write( "W" );
  770. 			Console.ResetColor( );
  771. 			Console.Error.WriteLine( "idth of the input box" );
  772.  
  773. 			Console.Error.WriteLine( "                     (default: {0}; minimum: {0}; maximum: screen width)", defwidth );
  774.  
  775. 			Console.Error.WriteLine( );
  776.  
  777. 			Console.Error.WriteLine( "Example: prompt for password" );
  778. 			Console.ForegroundColor = bold;
  779.  
  780. 			Console.Error.WriteLine( "InputBox.exe \"Enter your password:\" \"Login\" /S" );
  781. 			Console.ResetColor( );
  782.  
  783. 			Console.Error.WriteLine( );
  784.  
  785. 			Console.Error.WriteLine( "Example: fixed length hexadecimal input (enter as a single command line)" );
  786.  
  787. 			Console.ForegroundColor = bold;
  788. 			Console.Error.WriteLine( "InputBox.exe \"Enter a MAC address:\" \"MAC Address\" \"0022446688AA\"" );
  789.  
  790. 			Console.Error.WriteLine( "             /M:\">CC\\:CC\\:CC\\:CC\\:CC\\:CC\" /R:\"[0-9A-F]{2}(\\:[0-9A-F]{2}){5}\"" );
  791. 			Console.ResetColor( );
  792.  
  793. 			Console.Error.WriteLine( );
  794.  
  795. 			Console.Error.Write( "Notes:   For hidden input (" );
  796. 			Console.ForegroundColor = bold;
  797. 			Console.Error.Write( "/P" );
  798. 			Console.ResetColor( );
  799. 			Console.Error.Write( " and/or " );
  800. 			Console.ForegroundColor = bold;
  801. 			Console.Error.Write( "/S), " );
  802. 			Console.ResetColor( );
  803. 			Console.Error.Write( "), " );
  804. 			Console.ForegroundColor = bold;
  805. 			Console.Error.Write( "\"default\"" );
  806. 			Console.ResetColor( );
  807. 			Console.Error.WriteLine( " will be ignored." );
  808.  
  809. 			Console.Error.Write( "         Be careful with " );
  810. 			Console.ForegroundColor = bold;
  811. 			Console.Error.Write( "/N" );
  812. 			Console.ResetColor( );
  813. 			Console.Error.WriteLine( ", use doublequotes for the \"captured\" result," );
  814.  
  815. 			Console.Error.WriteLine( "         or redirect the result to a (temporary) file." );
  816.  
  817. 			Console.Error.Write( "         Show password (" );
  818. 			Console.ForegroundColor = bold;
  819. 			Console.Error.Write( "/S" );
  820. 			Console.ResetColor( );
  821. 			Console.Error.Write( ") implies hiding the input text (" );
  822. 			Console.ForegroundColor = bold;
  823. 			Console.Error.Write( "/P" );
  824. 			Console.ResetColor( );
  825. 			Console.Error.WriteLine( ")." );
  826.  
  827. 			Console.Error.Write( "         Use " );
  828. 			Console.ForegroundColor = bold;
  829. 			Console.Error.Write( "/M" );
  830. 			Console.ResetColor( );
  831. 			Console.Error.Write( " (without " );
  832. 			Console.ForegroundColor = bold;
  833. 			Console.Error.Write( "mask" );
  834. 			Console.ResetColor( );
  835. 			Console.Error.Write( ") to show detailed help on the " );
  836. 			Console.ForegroundColor = bold;
  837. 			Console.Error.Write( "mask" );
  838. 			Console.ResetColor( );
  839. 			Console.Error.WriteLine( " language." );
  840.  
  841. 			Console.Error.Write( "         Use " );
  842. 			Console.ForegroundColor = bold;
  843. 			Console.Error.Write( "/L" );
  844. 			Console.ResetColor( );
  845. 			Console.Error.Write( " for " );
  846. 			Console.ForegroundColor = bold;
  847. 			Console.Error.Write( "L" );
  848. 			Console.ResetColor( );
  849. 			Console.Error.WriteLine( "ocalized \"OK\" and \"Cancel\" button captions." );
  850.  
  851. 			Console.Error.Write( "         Custom captions require a " );
  852. 			Console.ForegroundColor = bold;
  853. 			Console.Error.Write( "string" );
  854. 			Console.ResetColor( );
  855. 			Console.Error.Write( " like " );
  856. 			Console.ForegroundColor = bold;
  857. 			Console.Error.WriteLine( "/L:\"OK=caption;Cancel=caption\"" );
  858. 			Console.ResetColor( );
  859.  
  860. 			Console.Error.WriteLine( "         (button=caption pairs separated by semicolons, each button optional)" );
  861.  
  862. 			Console.Error.WriteLine( "         Text from input is written to Standard Output only if \"OK\" is clicked." );
  863.  
  864. 			Console.Error.WriteLine( "         Return code is 0 for \"OK\", 1 for (command line) errors, 2 for" );
  865.  
  866. 			Console.Error.WriteLine( "         \"Cancel\", 3 on timeout, 4 if no regex or mask match." );
  867.  
  868. 			Console.Error.WriteLine( );
  869.  
  870. 			Console.Error.WriteLine( "Credits: On-the-fly form based on code by Gorkem Gencay on StackOverflow:" );
  871.  
  872. 			if ( !bw )
  873. 			{
  874. 				Console.ForegroundColor = ConsoleColor.DarkGray;
  875. 			}
  876. 			Console.Error.WriteLine( "         http://stackoverflow.com/questions/97097#17546909" );
  877. 			Console.ResetColor( );
  878.  
  879. 			Console.Error.WriteLine( "         Code to retrieve localized button captions by Martin Stoeckli:" );
  880.  
  881. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  882. 			Console.Error.WriteLine( "         http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources" );
  883. 			Console.ResetColor( );
  884.  
  885. 			Console.Error.WriteLine( );
  886.  
  887. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  888.  
  889. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  890.  
  891. 			return 1;
  892. 		}
  893.  
  894.  
  895. 		public static int ValidateAndShowResult( )
  896. 		{
  897. 			string input = String.Empty;
  898. 			// Read input from MaskedTextBox or TextBox
  899. 			if ( usemask )
  900. 			{
  901. 				input = maskedTextBox.Text;
  902. 				// Check if input complies with mask
  903. 				if ( !maskedTextBox.MaskCompleted )
  904. 				{
  905. 					return 4;
  906. 				}
  907. 			}
  908. 			else
  909. 			{
  910. 				input = textBox.Text;
  911. 			}
  912.  
  913. 			// Check if input complies with regex
  914. 			if ( regexset && !new Regex( pattern, RegexOptions.IgnoreCase ).IsMatch( input ) )
  915. 			{
  916. 				return 4;
  917. 			}
  918.  
  919. 			// Remove ampersands and redirection symbols unless /N switch was used
  920. 			if ( filtered )
  921. 			{
  922. 				input = new Regex( @"[&<>|]" ).Replace( input, String.Empty );
  923. 			}
  924.  
  925. 			// Remove doublequotes from output
  926. 			input = input.Replace( "\"", "" );
  927. 			Console.WriteLine( input );
  928. 			return 0;
  929. 		}
  930.  
  931.  
  932. 		public static void WriteTableRow( string col1text, string col2text, int col1percentage, bool col1bold = true, bool col2bold = false )
  933. 		{
  934. 			// Wrap text to fit in 2 columns
  935. 			oddrow = !oddrow;
  936. 			int windowwidth = Console.WindowWidth;
  937. 			int col1width = Convert.ToInt32( windowwidth * col1percentage / 100 );
  938. 			int col2width = windowwidth - col1width - 5; // Column separator = 4, subtract 1 extra to prevent automatic line wrap
  939. 			List<string> col1lines = new List<string>( );
  940. 			List<string> col2lines = new List<string>( );
  941. 			// Column 1
  942. 			if ( col1text.Length > col1width )
  943. 			{
  944. 				Regex regex = new Regex( @".{1," + col1width + @"}(?=\s|$)" );
  945. 				if ( regex.IsMatch( col1text ) )
  946. 				{
  947. 					MatchCollection matches = regex.Matches( col1text );
  948. 					foreach ( Match match in matches )
  949. 					{
  950. 						col1lines.Add( match.ToString( ).Trim( ) );
  951. 					}
  952. 				}
  953. 				else
  954. 				{
  955. 					while ( col1text.Length > 0 )
  956. 					{
  957. 						col1lines.Add( col1text.Trim( ).Substring( 0, Math.Min( col1width, col1text.Length ) ) );
  958. 						col1text = col1text.Substring( Math.Min( col1width, col1text.Length ) ).Trim( );
  959. 					}
  960. 				}
  961. 			}
  962. 			else
  963. 			{
  964. 				col1lines.Add( col1text.Trim( ) );
  965. 			}
  966. 			// Column 2
  967. 			if ( col2text.Length > col2width )
  968. 			{
  969. 				Regex regex = new Regex( @".{1," + col2width + @"}(?=\s|$)" );
  970. 				if ( regex.IsMatch( col2text ) )
  971. 				{
  972. 					MatchCollection matches = regex.Matches( col2text );
  973. 					foreach ( Match match in matches )
  974. 					{
  975. 						col2lines.Add( match.ToString( ).Trim( ) );
  976. 					}
  977. 				}
  978. 				else
  979. 				{
  980. 					while ( col2text.Length > 0 )
  981. 					{
  982. 						col2lines.Add( col2text.Trim( ).Substring( 0, Math.Min( col2width, col2text.Length ) ) );
  983. 						col2text = col2text.Substring( Math.Min( col2width, col2text.Length ) ).Trim( );
  984. 					}
  985. 				}
  986. 			}
  987. 			else
  988. 			{
  989. 				col2lines.Add( col2text.Trim( ) );
  990. 			}
  991. 			for ( int i = 0; i < Math.Max( col1lines.Count, col2lines.Count ); i++ )
  992. 			{
  993. 				if ( oddrow && !bw )
  994. 				{
  995. 					Console.BackgroundColor = ConsoleColor.DarkGray;
  996. 				}
  997. 				if ( col1bold || oddrow )
  998. 				{
  999. 					Console.ForegroundColor = bold;
  1000. 				}
  1001. 				Console.Write( "{0,-" + col1width + "}    ", ( i < col1lines.Count ? col1lines[i] : String.Empty ) );
  1002. 				Console.ResetColor( );
  1003. 				if ( oddrow && !bw )
  1004. 				{
  1005. 					Console.BackgroundColor = ConsoleColor.DarkGray;
  1006. 				}
  1007. 				if ( col2bold || oddrow )
  1008. 				{
  1009. 					Console.ForegroundColor = bold;
  1010. 				}
  1011. 				Console.WriteLine( "{0,-" + col2width + "}", ( i < col2lines.Count ? col2lines[i] : String.Empty ) );
  1012. 				Console.ResetColor( );
  1013. 			}
  1014. 		}
  1015.  
  1016.  
  1017. 		public static int HelpMessage( string subject )
  1018. 		{
  1019. 			switch ( subject.ToLower( ) )
  1020. 			{
  1021. 				case "mask":
  1022. 					int col1perc = 13;
  1023. 					Console.Error.Write( "Help for command line switch " );
  1024. 					Console.ForegroundColor = bold;
  1025. 					Console.Error.WriteLine( "/M:mask" );
  1026. 					Console.ResetColor( );
  1027. 					Console.Error.WriteLine( );
  1028. 					Console.Error.Write( "The " );
  1029. 					Console.ForegroundColor = bold;
  1030. 					Console.Error.Write( "mask" );
  1031. 					Console.ResetColor( );
  1032. 					Console.Error.WriteLine( " \"language\" is based on the Masked Edit control in Visual Basic 6.0:" );
  1033. 					if ( !bw )
  1034. 					{
  1035. 						Console.ForegroundColor = ConsoleColor.DarkGray;
  1036. 					}
  1037. 					string url1 = "http://msdn.microsoft.com/en-us/library/";
  1038. 					string url2 = "system.windows.forms.maskedtextbox.mask.aspx#remarksToggle";
  1039. 					if ( url1.Length + url2.Length > Console.WindowWidth )
  1040. 					{
  1041. 						Console.Error.WriteLine( url1 );
  1042. 						Console.Error.WriteLine( url2 );
  1043. 					}
  1044. 					else
  1045. 					{
  1046. 						Console.Error.WriteLine( url1 + url2 );
  1047. 					}
  1048. 					Console.ResetColor( );
  1049. 					Console.Error.WriteLine( );
  1050. 					WriteTableRow( "Masking element", "Description", col1perc, true, true );
  1051. 					WriteTableRow( "0", "Digit, required. This element will accept any single digit between 0 and 9.", col1perc );
  1052. 					WriteTableRow( "9", "Digit or space, optional.", col1perc );
  1053. 					WriteTableRow( "#", "Digit or space, optional. If this position is blank in the mask, it will be rendered as a space in the Text property. Plus (+) and minus (-) signs are allowed.", col1perc );
  1054. 					WriteTableRow( "L", "Letter, required. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z] in regular expressions.", col1perc );
  1055. 					WriteTableRow( "?", "Letter, optional. Restricts input to the ASCII letters a-z and A-Z. This mask element is equivalent to [a-zA-Z]? in regular expressions.", col1perc );
  1056. 					WriteTableRow( "&", "Character, required. Any non-control character. If ASCII only is set (/A), this element behaves like the \"A\" element.", col1perc );
  1057. 					WriteTableRow( "C", "Character, optional. Any non-control character. If ASCII only is set (/A), this element behaves like the \"a\" element.", col1perc );
  1058. 					WriteTableRow( "A", "Alphanumeric, required. If ASCII only is set (/A), the only characters it will accept are the ASCII letters a-z and A-Z and numbers. This mask element behaves like the \"&\" element.", col1perc );
  1059. 					WriteTableRow( "a", "Alphanumeric, optional. If ASCII only is set (/A), the only characters it will accept are the ASCII letters a-z and A-Z and numbers. This mask element behaves like the \"C\" element.", col1perc );
  1060. 					WriteTableRow( ".", "Decimal placeholder.", col1perc );
  1061. 					WriteTableRow( ",", "Thousands placeholder.", col1perc );
  1062. 					WriteTableRow( ":", "Time separator.", col1perc );
  1063. 					WriteTableRow( "/", "Date separator.", col1perc );
  1064. 					WriteTableRow( "$", "Currency symbol.", col1perc );
  1065. 					WriteTableRow( "<", "Shift down. Converts all characters that follow to lowercase.", col1perc );
  1066. 					WriteTableRow( ">", "Shift up. Converts all characters that follow to uppercase.", col1perc );
  1067. 					WriteTableRow( "|", "Disable a previous shift up or shift down.", col1perc );
  1068. 					WriteTableRow( @"\", "Escape. Escapes a mask character, turning it into a literal. \"\\\\\" is the escape sequence for a backslash.", col1perc );
  1069. 					WriteTableRow( "All other characters", "Literals. All non-mask elements will appear as themselves within MaskedTextBox. Literals always occupy a static position in the mask at run time, and cannot be moved or deleted by the user.", col1perc );
  1070. 					break;
  1071. 				default:
  1072. 					return ErrorMessage( );
  1073. 			}
  1074. 			return 1;
  1075. 		}
  1076.  
  1077.  
  1078. 		#region Get Localized Captions
  1079.  
  1080. 		// Code to retrieve localized captions by Martin Stoeckli
  1081. 		// http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources
  1082.  
  1083. 		/// <summary>
  1084. 		/// Searches for a text resource in a Windows library.
  1085. 		/// Sometimes, using the existing Windows resources, you can make your code
  1086. 		/// language independent and you don't have to care about translation problems.
  1087. 		/// </summary>
  1088. 		/// <example>
  1089. 		///   btnCancel.Text = Load("user32.dll", 801, "Cancel");
  1090. 		///   btnYes.Text = Load("user32.dll", 805, "Yes");
  1091. 		/// </example>
  1092. 		/// <param name="libraryName">Name of the windows library like "user32.dll"
  1093. 		/// or "shell32.dll"</param>
  1094. 		/// <param name="ident">Id of the string resource.</param>
  1095. 		/// <param name="defaultText">Return this text, if the resource string could
  1096. 		/// not be found.</param>
  1097. 		/// <returns>Requested string if the resource was found,
  1098. 		/// otherwise the <paramref name="defaultText"/></returns>
  1099. 		public static string Load( string libraryName, UInt32 ident, string defaultText )
  1100. 		{
  1101. 			IntPtr libraryHandle = GetModuleHandle( libraryName );
  1102. 			if ( libraryHandle != IntPtr.Zero )
  1103. 			{
  1104. 				StringBuilder sb = new StringBuilder( 1024 );
  1105. 				int size = LoadString( libraryHandle, ident, sb, 1024 );
  1106. 				if ( size > 0 )
  1107. 					return sb.ToString( );
  1108. 			}
  1109. 			return defaultText;
  1110. 		}
  1111.  
  1112. 		[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
  1113. 		private static extern IntPtr GetModuleHandle( string lpModuleName );
  1114.  
  1115. 		[DllImport( "user32.dll", CharSet = CharSet.Auto )]
  1116. 		private static extern int LoadString( IntPtr hInstance, UInt32 uID, StringBuilder lpBuffer, Int32 nBufferMax );
  1117.  
  1118. 		#endregion Get Localized Captions
  1119. 	}
  1120. }
  1121.  

page last uploaded: 2017-08-21, 14:26