Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for printerselectbox.cs

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

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Management;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Windows.Forms;
  10.  
  11.  
  12. namespace RobvanderWoude
  13. {
  14. 	class PrinterSelectBox
  15. 	{
  16. 		public static string progver = "2.06";
  17.  
  18. 		#region Global Variables
  19.  
  20. 		public static ComboBox combobox;
  21. 		public static Label statusfield;
  22. 		public static Label typefield;
  23. 		public static Label wherefield;
  24. 		public static Label commentfield;
  25. 		public static List<string[]> localprinters = new List<string[]>( );
  26. 		public static List<string[]> networkprinters = new List<string[]>( );
  27.  
  28. 		public const int defaultheight = 220;
  29. 		public const int defaultwidth = 400;
  30.  
  31. 		#endregion Global Variables
  32.  
  33.  
  34. 		[STAThread]
  35. 		static int Main( string[] args )
  36. 		{
  37. 			try
  38. 			{
  39. 				// On-the fly form inspired by Gorkem Gencay's code on StackOverflow.com:
  40. 				// http://stackoverflow.com/questions/97097/what-is-the-c-sharp-version-of-vb-nets-inputdialog#17546909
  41.  
  42. 				#region Initialize Variables
  43.  
  44. 				string selected;
  45. 				string title = "Select Printer";
  46. 				bool titleset = false;
  47. 				string preselected = String.Empty;
  48. 				bool preselectedset = false;
  49. 				string cancelcaption = "&Cancel";
  50. 				string okcaption = "&OK";
  51. 				string printcaption = "&Print";
  52. 				bool printcaptionset = false;
  53. 				SortedList localprinternames = new SortedList( );
  54. 				SortedList networkprinternames = new SortedList( );
  55. 				bool localonly = false;
  56. 				bool networkonly = false;
  57. 				int height = defaultheight;
  58. 				int width = defaultwidth;
  59. 				string localizationstring = String.Empty;
  60. 				bool localizedcaptionset = false;
  61. 				string namecaption = "Name";
  62. 				string statuscaption = "Status";
  63. 				string typecaption = "Type";
  64. 				string wherecaption = "Where";
  65. 				string commentcaption = "Comment";
  66.  
  67. 				#endregion Initialize Variables
  68.  
  69.  
  70. 				#region Populate Printers List
  71.  
  72. 				QueryPrinters( );
  73.  
  74. 				localprinternames.Clear( );
  75. 				foreach ( string[] prn in localprinters )
  76. 				{
  77. 					localprinternames.Add( prn[0], prn[5] );
  78. 					// Make the default printer the initial preselected printer in the dropdown list
  79. 					if ( prn[5] == "1" )
  80. 					{
  81. 						preselected = prn[0];
  82. 					}
  83. 				}
  84.  
  85. 				networkprinternames.Clear( );
  86. 				foreach ( string[] prn in networkprinters )
  87. 				{
  88. 					networkprinternames.Add( prn[0], prn[5] );
  89. 					// Make the default printer the initial preselected printer in the dropdown list
  90. 					if ( prn[5] == "1" )
  91. 					{
  92. 						preselected = prn[0];
  93. 					}
  94. 				}
  95.  
  96. 				#endregion Populate Printers List
  97.  
  98.  
  99. 				#region Parse Command Line
  100.  
  101. 				if ( args.Length > 5 )
  102. 				{
  103. 					return ShowHelp( );
  104. 				}
  105. 				foreach ( string arg in args )
  106. 				{
  107. 					if ( arg == "/?" )
  108. 					{
  109. 						return ShowHelp( );
  110. 					}
  111. 				}
  112.  
  113. 				if ( args.Length > 0 )
  114. 				{
  115. 					foreach ( string arg in args )
  116. 					{
  117. 						if ( arg.Length > 0 && arg[0] == '/' )
  118. 						{
  119. 							if ( arg.Length > 5 && arg.Substring( 0, 3 ).ToUpper( ) == "/H:" )
  120. 							{
  121. 								if ( height != defaultheight )
  122. 								{
  123. 									return ShowHelp( "Duplicate command line switch /H" );
  124. 								}
  125. 								try
  126. 								{
  127. 									height = Convert.ToInt32( arg.Substring( 3 ) );
  128. 								}
  129. 								catch ( Exception )
  130. 								{
  131. 									return ShowHelp( "Invalid height \"{0}\"", arg );
  132. 								}
  133. 								if ( height > Screen.PrimaryScreen.WorkingArea.Height || height < defaultheight )
  134. 								{
  135. 									return ShowHelp( "Window height must be in range {0}..{1}", defaultheight.ToString( ), Screen.PrimaryScreen.WorkingArea.Height.ToString( ) );
  136. 								}
  137. 							}
  138. 							else if ( arg.Length > 1 && arg.Substring( 0, 2 ).ToUpper( ) == "/L" )
  139. 							{
  140. 								if ( localizedcaptionset )
  141. 								{
  142. 									return ShowHelp( "Duplicate command line switch /L" );
  143. 								}
  144. 								localizedcaptionset = true;
  145. 								if ( arg.Length > 3 )
  146. 								{
  147. 									if ( arg[2] == ':' )
  148. 									{
  149. 										localizationstring = arg.Substring( 3 );
  150. 									}
  151. 									else
  152. 									{
  153. 										return ShowHelp( "Invalid command line switch {0}", arg );
  154. 									}
  155. 								}
  156. 							}
  157. 							else if ( arg.Length > 1 && arg.Substring( 0, 2 ).ToUpper( ) == "/N" )
  158. 							{
  159. 								if ( localonly )
  160. 								{
  161. 									return ShowHelp( "Duplicate command line switch /N" );
  162. 								}
  163. 								if ( networkonly )
  164. 								{
  165. 									return ShowHelp( "Command line switches /N and /O are mutually exclusive" );
  166. 								}
  167. 								networkonly = true;
  168. 								localonly = false;
  169. 							}
  170. 							else if ( arg.Length > 1 && arg.Substring( 0, 2 ).ToUpper( ) == "/O" )
  171. 							{
  172. 								if ( networkonly )
  173. 								{
  174. 									return ShowHelp( "Duplicate command line switch /O" );
  175. 								}
  176. 								if ( localonly )
  177. 								{
  178. 									return ShowHelp( "Command line switches /N and /O are mutually exclusive" );
  179. 								}
  180. 								networkonly = false;
  181. 								localonly = true;
  182. 							}
  183. 							else if ( arg.Length > 1 && arg.Substring( 0, 2 ).ToUpper( ) == "/P" )
  184. 							{
  185. 								if ( printcaptionset )
  186. 								{
  187. 									return ShowHelp( "Duplicate command line switch /P" );
  188. 								}
  189. 								printcaptionset = true;
  190. 								if ( arg.Length > 3 )
  191. 								{
  192. 									if ( arg[2] == ':' )
  193. 									{
  194. 										printcaption = arg.Substring( 3 );
  195. 									}
  196. 									else
  197. 									{
  198. 										return ShowHelp( "Invalid command line switch {0}", arg );
  199. 									}
  200. 								}
  201. 							}
  202. 							else if ( arg.Length > 5 && arg.Substring( 0, 3 ).ToUpper( ) == "/W:" )
  203. 							{
  204. 								if ( width != defaultwidth )
  205. 								{
  206. 									return ShowHelp( "Duplicate command line switch /W" );
  207. 								}
  208. 								try
  209. 								{
  210. 									width = Convert.ToInt32( arg.Substring( 3 ) );
  211. 								}
  212. 								catch ( Exception )
  213. 								{
  214. 									return ShowHelp( "Invalid width \"{0}\"", arg );
  215. 								}
  216. 								if ( width > Screen.PrimaryScreen.WorkingArea.Width || width < defaultwidth )
  217. 								{
  218. 									return ShowHelp( "Window width must be in range {0}..{1}", defaultwidth.ToString( ), Screen.PrimaryScreen.WorkingArea.Width.ToString( ) );
  219. 								}
  220. 							}
  221. 							else
  222. 							{
  223. 								return ShowHelp( "Invalid command line switch {0}", arg );
  224. 							}
  225. 						}
  226. 						else
  227. 						{
  228. 							if ( !titleset )
  229. 							{
  230. 								title = arg;
  231. 								titleset = true;
  232. 							}
  233. 							else if ( !preselectedset )
  234. 							{
  235. 								// Make the specified printer the selected one in the dropdown list
  236. 								if ( localprinternames.ContainsKey( arg ) )
  237. 								{
  238. 									preselected = arg;
  239. 								}
  240. 								else
  241. 								{
  242. 									string pattern = arg;
  243. 									bool match = false;
  244. 									foreach ( string printer in localprinternames.Keys )
  245. 									{
  246. 										if ( Regex.IsMatch( printer, pattern, RegexOptions.IgnoreCase ) )
  247. 										{
  248. 											match = true;
  249. 											preselected = printer;
  250. 											break; // Search no further after first match
  251. 										}
  252. 									}
  253. 									if ( !match )
  254. 									{
  255. 										return ShowHelp( "No printer name found matching \"{0}\"", preselected );
  256. 									}
  257. 								}
  258. 								preselectedset = true;
  259. 							}
  260. 							else if ( width == defaultwidth ) // For backwards compatibility only; use /W switch instead
  261. 							{
  262. 								try
  263. 								{
  264. 									width = Convert.ToInt32( arg );
  265. 								}
  266. 								catch ( Exception )
  267. 								{
  268. 									return ShowHelp( "Invalid width \"{0}\"", arg );
  269. 								}
  270. 							}
  271. 							else
  272. 							{
  273. 								return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  274. 							}
  275. 						}
  276. 					}
  277. 				}
  278.  
  279. 				if ( localonly && localprinters.Count == 0 )
  280. 				{
  281. 					return ShowHelp( "No local printers found" );
  282. 				}
  283.  
  284. 				if ( networkonly && networkprinters.Count == 0 )
  285. 				{
  286. 					return ShowHelp( "No network printers found" );
  287. 				}
  288.  
  289. 				#endregion Parse Command Line
  290.  
  291.  
  292. 				#region Set Localized Captions
  293.  
  294. 				if ( localizedcaptionset )
  295. 				{
  296. 					cancelcaption = Load( "user32.dll", 801, cancelcaption );
  297. 					okcaption = Load( "user32.dll", 800, okcaption );
  298. 					if ( !String.IsNullOrWhiteSpace( localizationstring ) )
  299. 					{
  300. 						string pattern = @"^((Name|Status|Type|Where|Comment|OK|Cancel)=[^;\""]*;)*((Name|Status|Type|Where|Comment|OK|Cancel)=[^;\""]*);?$";
  301. 						Regex regex = new Regex( pattern, RegexOptions.IgnoreCase );
  302. 						if ( regex.IsMatch( localizationstring ) )
  303. 						{
  304. 							string[] locstrings = localizationstring.Split( ";".ToCharArray( ) );
  305. 							foreach ( string locstring in locstrings )
  306. 							{
  307. 								string key = locstring.Substring( 0, locstring.IndexOf( '=' ) );
  308. 								string val = locstring.Substring( Math.Min( locstring.IndexOf( '=' ) + 1, locstring.Length - 1 ) );
  309. 								if ( !String.IsNullOrWhiteSpace( val ) )
  310. 								{
  311. 									switch ( key.ToUpper( ) )
  312. 									{
  313. 										case "NAME":
  314. 											namecaption = val;
  315. 											break;
  316. 										case "STATUS":
  317. 											statuscaption = val;
  318. 											break;
  319. 										case "TYPE":
  320. 											typecaption = val;
  321. 											break;
  322. 										case "WHERE":
  323. 											wherecaption = val;
  324. 											break;
  325. 										case "COMMENT":
  326. 											commentcaption = val;
  327. 											break;
  328. 										case "OK":
  329. 											okcaption = val;
  330. 											break;
  331. 										case "CANCEL":
  332. 											cancelcaption = val;
  333. 											break;
  334. 										default:
  335. 											return ShowHelp( "Invalid localization key \"{0}\"", key );
  336. 									}
  337. 								}
  338. 							}
  339. 						}
  340. 						else
  341. 						{
  342. 							return ShowHelp( "Invalid localization string:\n\t{0}", localizationstring );
  343. 						}
  344. 					}
  345. 				}
  346.  
  347. 				#endregion Set Localized Captions
  348.  
  349.  
  350. 				#region Build Form
  351.  
  352. 				// Create the dialog box
  353. 				Form printerSelect = new Form( );
  354. 				Size size = new Size( width, height );
  355. 				printerSelect.FormBorderStyle = FormBorderStyle.FixedDialog;
  356. 				printerSelect.MaximizeBox = false;
  357. 				printerSelect.MinimizeBox = false;
  358. 				printerSelect.StartPosition = FormStartPosition.CenterParent;
  359. 				printerSelect.ClientSize = size;
  360. 				if ( printcaptionset && !titleset )
  361. 				{
  362. 					title = printcaption.Replace( "&", String.Empty );
  363. 				}
  364. 				printerSelect.Text = title;
  365.  
  366. 				// Label "Name:" for printer name
  367. 				Label labelName = new Label( );
  368. 				labelName.Size = new Size( 70, 20 );
  369. 				labelName.Location = new Point( 10, 27 );
  370. 				labelName.Text = namecaption + ":";
  371. 				printerSelect.Controls.Add( labelName );
  372.  
  373. 				// Dropdown list to contain available printer names
  374. 				combobox = new ComboBox( );
  375. 				combobox.Size = new Size( size.Width - 100, 25 );
  376. 				combobox.Location = new Point( 90, 25 );
  377. 				combobox.AutoCompleteMode = AutoCompleteMode.Append;
  378. 				combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
  379. 				combobox.DropDownStyle = ComboBoxStyle.DropDownList;
  380. 				combobox.SelectedIndexChanged += new EventHandler( combobox_SelectedIndexChanged );
  381. 				printerSelect.Controls.Add( combobox );
  382.  
  383. 				// Label "Status:" for selected printer's current status
  384. 				Label labelStatus = new Label( );
  385. 				labelStatus.Size = new Size( 70, 20 );
  386. 				labelStatus.Location = new Point( 10, 57 );
  387. 				labelStatus.Text = statuscaption + ":";
  388. 				printerSelect.Controls.Add( labelStatus );
  389.  
  390. 				// Label to contain selected printer's current status
  391. 				statusfield = new Label( );
  392. 				statusfield.Size = new Size( size.Width - 10 - 80, 20 );
  393. 				statusfield.Location = new Point( 90, 57 );
  394. 				statusfield.Text = "Status Value";
  395. 				printerSelect.Controls.Add( statusfield );
  396.  
  397. 				// Label "Type:" for selected printer's type description
  398. 				Label labelType = new Label( );
  399. 				labelType.Size = new Size( 70, 20 );
  400. 				labelType.Location = new Point( 10, 82 );
  401. 				labelType.Text = typecaption + ":";
  402. 				printerSelect.Controls.Add( labelType );
  403.  
  404. 				// Label to contain selected printer's type description
  405. 				typefield = new Label( );
  406. 				typefield.Size = new Size( size.Width - 10 - 80, 20 );
  407. 				typefield.Location = new Point( 90, 82 );
  408. 				typefield.Text = "Type Value";
  409. 				printerSelect.Controls.Add( typefield );
  410.  
  411. 				// Label "Where:" for selected printer's location or printer port
  412. 				Label labelWhere = new Label( );
  413. 				labelWhere.Size = new Size( 70, 20 );
  414. 				labelWhere.Location = new Point( 10, 107 );
  415. 				labelWhere.Text = wherecaption + ":";
  416. 				printerSelect.Controls.Add( labelWhere );
  417.  
  418. 				// Label to contain selected printer's location or printer port
  419. 				wherefield = new Label( );
  420. 				wherefield.Size = new Size( size.Width - 10 - 80, 20 );
  421. 				wherefield.Location = new Point( 90, 107 );
  422. 				wherefield.Text = "Where Value";
  423. 				printerSelect.Controls.Add( wherefield );
  424.  
  425. 				// Label "Comment:" for selected printer's optional comment line
  426. 				Label labelComment = new Label( );
  427. 				labelComment.Size = new Size( 70, 20 );
  428. 				labelComment.Location = new Point( 10, 132 );
  429. 				labelComment.Text = commentcaption + ":";
  430. 				printerSelect.Controls.Add( labelComment );
  431.  
  432. 				// Label to contain selected printer's optional comment line
  433. 				commentfield = new Label( );
  434. 				commentfield.Size = new Size( size.Width - 10 - 80, 20 );
  435. 				commentfield.Location = new Point( 90, 132 );
  436. 				commentfield.Text = "Comment Value";
  437. 				printerSelect.Controls.Add( commentfield );
  438.  
  439. 				Button okButton = new Button( );
  440. 				okButton.DialogResult = DialogResult.OK;
  441. 				okButton.Name = "okButton";
  442. 				okButton.Size = new Size( 80, 25 );
  443. 				if ( printcaptionset )
  444. 				{
  445. 					okButton.Text = printcaption;
  446. 				}
  447. 				else
  448. 				{
  449. 					okButton.Text = okcaption;
  450. 				}
  451. 				okButton.Location = new Point( size.Width / 2 - 10 - 80, 175 );
  452. 				printerSelect.Controls.Add( okButton );
  453.  
  454. 				Button cancelButton = new Button( );
  455. 				cancelButton.DialogResult = DialogResult.Cancel;
  456. 				cancelButton.Name = "cancelButton";
  457. 				cancelButton.Size = new Size( 80, 25 );
  458. 				cancelButton.Text = cancelcaption;
  459. 				cancelButton.Location = new Point( size.Width / 2 + 10, 175 );
  460. 				printerSelect.Controls.Add( cancelButton );
  461.  
  462. 				printerSelect.AcceptButton = okButton;  // OK on Enter
  463. 				printerSelect.CancelButton = cancelButton; // Cancel on Esc
  464. 				printerSelect.Activate( );
  465.  
  466. 				#endregion Build Form
  467.  
  468.  
  469. 				#region Populate Dropdown with Local Printers
  470.  
  471. 				int index = 0;
  472. 				if ( !networkonly )
  473. 				{
  474. 					foreach ( string prn in localprinternames.Keys )
  475. 					{
  476. 						combobox.Items.Add( prn );
  477. 						// Select the preselected printer if specified, or the default printer otherwise
  478. 						if ( prn.ToLower( ) == preselected.ToLower( ) )
  479. 						{
  480. 							combobox.SelectedIndex = index;
  481. 							foreach ( string[] printer in localprinters )
  482. 							{
  483. 								if ( printer[0].ToLower( ) == preselected.ToLower( ) )
  484. 								{
  485. 									statusfield.Text = printer[1];
  486. 									typefield.Text = printer[2];
  487. 									wherefield.Text = printer[3];
  488. 									commentfield.Text = printer[4];
  489. 								}
  490. 							}
  491. 						}
  492. 						index += 1;
  493. 					}
  494. 				}
  495.  
  496. 				#endregion Populate Dropdown with Local Printers
  497.  
  498.  
  499. 				#region Populate Dropdown with Network Printers
  500.  
  501. 				if ( !localonly )
  502. 				{
  503. 					foreach ( string prn in networkprinternames.Keys )
  504. 					{
  505. 						combobox.Items.Add( prn );
  506. 						// Select the preselected printer if specified, or the default printer otherwise
  507. 						if ( prn.ToLower( ) == preselected.ToLower( ) )
  508. 						{
  509. 							combobox.SelectedIndex = index;
  510. 							foreach ( string[] printer in networkprinters )
  511. 							{
  512. 								if ( printer[0].ToLower( ) == preselected.ToLower( ) )
  513. 								{
  514. 									statusfield.Text = printer[1];
  515. 									typefield.Text = printer[2];
  516. 									wherefield.Text = printer[3];
  517. 									commentfield.Text = printer[4];
  518. 								}
  519. 							}
  520. 						}
  521. 						index += 1;
  522. 					}
  523. 				}
  524.  
  525. 				#endregion Populate Dropdown with Network Printers
  526.  
  527.  
  528. 				DialogResult result = printerSelect.ShowDialog( );
  529. 				if ( result == DialogResult.OK )
  530. 				{
  531. 					selected = combobox.SelectedItem.ToString( );
  532. 					Console.WriteLine( selected );
  533. 					return 0;
  534. 				}
  535. 				else
  536. 				{
  537. 					return 2;
  538. 				}
  539. 			}
  540. 			catch ( Exception e )
  541. 			{
  542. 				return ShowHelp( e.Message );
  543. 			}
  544. 		}
  545.  
  546.  
  547. 		public static void combobox_SelectedIndexChanged( object sender, EventArgs e )
  548. 		{
  549. 			string printername = combobox.Text;
  550. 			foreach ( string[] prn in localprinters )
  551. 			{
  552. 				if ( prn[0] == printername )
  553. 				{
  554. 					statusfield.Text = prn[1];
  555. 					typefield.Text = prn[2];
  556. 					wherefield.Text = prn[3];
  557. 					commentfield.Text = prn[4];
  558. 				}
  559. 			}
  560. 		}
  561.  
  562.  
  563. 		public static void QueryPrinters( )
  564. 		{
  565. 			localprinters.Clear( );
  566. 			networkprinters.Clear( );
  567.  
  568. 			string query = "SELECT * FROM Win32_Printer";
  569. 			ManagementObjectSearcher searcher = new ManagementObjectSearcher( "root\\CIMV2", query );
  570. 			foreach ( ManagementObject queryObj in searcher.Get( ) )
  571. 			{
  572. 				string printer = (string) queryObj["DeviceID"];
  573. 				UInt32 printerstatus = Convert.ToUInt32( queryObj["ExtendedPrinterStatus"] );
  574. 				string printertype = (string) queryObj["DriverName"];
  575. 				string printerlocation = (string) queryObj["Location"];
  576. 				string printerport = (string) queryObj["PortName"];
  577. 				string printercomment = (string) queryObj["Comment"];
  578. 				bool isdefault = (bool) queryObj["Default"];
  579. 				bool islocal = (bool) queryObj["Local"];
  580. 				bool isnetwork = (bool) queryObj["Network"];
  581. 				string[] printerproperties = new string[6];
  582. 				printerproperties[0] = printer;
  583. 				printerproperties[1] = ( (WMIPrinterStatus) printerstatus ).ToString( );
  584. 				printerproperties[2] = printertype;
  585. 				if ( String.IsNullOrWhiteSpace( printerlocation ) )
  586. 				{
  587. 					printerproperties[3] = printerport;
  588. 				}
  589. 				else
  590. 				{
  591. 					printerproperties[3] = printerlocation;
  592. 				}
  593. 				printerproperties[4] = printercomment;
  594. 				printerproperties[5] = ( isdefault ? "1" : "0" );
  595. 				if ( islocal )
  596. 				{
  597. 					localprinters.Add( printerproperties );
  598. 				}
  599. 				else if ( isnetwork )
  600. 				{
  601. 					networkprinters.Add( printerproperties );
  602. 				}
  603. 			}
  604. 		}
  605.  
  606.  
  607. 		public static void UpdateFields( )
  608. 		{
  609. 			string printername = combobox.SelectedValue.ToString( );
  610. 			foreach ( string[] prn in localprinters )
  611. 			{
  612. 				if ( prn[0] == printername )
  613. 				{
  614. 					statusfield.Text = prn[1];
  615. 					typefield.Text = prn[2];
  616. 					wherefield.Text = prn[3];
  617. 					commentfield.Text = prn[4];
  618. 				}
  619. 			}
  620. 		}
  621.  
  622.  
  623. 		public static int ShowHelp( params string[] errmsg )
  624. 		{
  625. 			#region Help Text
  626.  
  627. 			/*
  628. 			PrinterSelectBox,  Version 2.06
  629. 			Batch tool to present a Printer Select dialog and return the selected printer
  630.  
  631. 			Usage:    PRINTERSELECTBOX  [ "title"  [ "selected" ] ]  [ options ]
  632.  
  633. 			Where:    "title"     is the optional caption in the title bar
  634. 			          "selected"  is the optional selected printer, either its full name or
  635. 			                      a regular expression (default: the default printer name)
  636.  
  637. 			Options:  /H:height   window Height (def: 220; min: 220; max: screen height)
  638. 			          /L[:string] Use Localized or custom captions (see Notes)
  639. 			          /N          list Network printers only (default: list all printers)
  640. 			          /O          list lOcal printers only   (default: list all printers)
  641. 			          /P[:text]   Alternative "OK" button caption "Print" or "text"
  642. 			          /W:width    window Width (default: 400; min: 400; max: screen width)
  643.  
  644. 			Notes:    Use /L for Localized "OK" and "Cancel" button captions only.
  645. 			          Custom captions require a "localization string" in the format
  646. 			          /L:"key=value;key=value;..." e.g. for Dutch on English computers:
  647. 			          /L:"Name=Naam;Where=Lokatie;Comment=Opmerking;Cancel=Annuleren"
  648. 			          The name of the selected printer is written to Standard Out if the
  649. 			          "OK" button is clicked, otherwise an empty string is returned.
  650. 			          If "selected" is specified, the program will try an exact (literal)
  651. 			          match first; if no match is found, "selected" will be interpreted as
  652. 			          a regular expression, and the first match in the sorted printer list
  653. 			          will be used.
  654. 			          If no "title" is specified and /P is used, the alternative "OK"
  655. 			          button caption ("Print" or "text") will be used for "title" too.
  656. 			          Return code 0 for "OK", 1 for (command line) errors, 2 for "Cancel".
  657.  
  658. 			Credits:  On-the-fly form based on code by Gorkem Gencay on StackOverflow:
  659. 			          http://stackoverflow.com/questions/97097
  660. 			          /what-is-the-c-sharp-version-of-vb-nets-inputdialog#17546909
  661. 			          Code to retrieve localized button captions by Martin Stoeckli:
  662. 			          http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources
  663.  
  664. 			Written by Rob van der Woude
  665. 			http://www.robvanderwoude.com
  666. 			*/
  667.  
  668. 			#endregion Help Text
  669.  
  670.  
  671. 			#region Error Message
  672.  
  673. 			if ( errmsg.Length > 0 )
  674. 			{
  675. 				List<string> errargs = new List<string>( errmsg );
  676. 				errargs.RemoveAt( 0 );
  677. 				Console.Error.WriteLine( );
  678. 				Console.ForegroundColor = ConsoleColor.Red;
  679. 				Console.Error.Write( "ERROR:\t" );
  680. 				Console.ForegroundColor = ConsoleColor.White;
  681. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  682. 				Console.ResetColor( );
  683. 			}
  684.  
  685. 			#endregion Error Message
  686.  
  687.  
  688. 			#region Show help text
  689.  
  690. 			Console.Error.WriteLine( );
  691.  
  692. 			Console.Error.WriteLine( "PrinterSelectBox,  Version {0}", progver );
  693.  
  694. 			Console.Error.WriteLine( "Batch tool to present a Printer Select dialog and return the selected printer" );
  695.  
  696. 			Console.Error.WriteLine( );
  697.  
  698. 			Console.Error.Write( "Usage:    " );
  699. 			Console.ForegroundColor = ConsoleColor.White;
  700. 			Console.Error.WriteLine( "PRINTERSELECTBOX  [ \"title\"  [ \"selected\" ] ]  [ options ]" );
  701. 			Console.ResetColor( );
  702.  
  703. 			Console.Error.WriteLine( );
  704.  
  705. 			Console.Error.Write( "Where:    " );
  706. 			Console.ForegroundColor = ConsoleColor.White;
  707. 			Console.Error.Write( "\"title\"" );
  708. 			Console.ResetColor( );
  709. 			Console.Error.WriteLine( "     is the optional caption in the title bar" );
  710.  
  711. 			Console.ForegroundColor = ConsoleColor.White;
  712. 			Console.Error.Write( "          \"selected\"" );
  713. 			Console.ResetColor( );
  714. 			Console.Error.WriteLine( "  is the optional selected printer, either its full name or" );
  715.  
  716. 			Console.Error.WriteLine( "                      a regular expression (default: the default printer name)" );
  717.  
  718. 			Console.Error.WriteLine( );
  719.  
  720. 			Console.Error.Write( "Options:  " );
  721. 			Console.ForegroundColor = ConsoleColor.White;
  722. 			Console.Error.Write( "/H:height" );
  723. 			Console.ResetColor( );
  724. 			Console.Error.Write( "   window " );
  725. 			Console.ForegroundColor = ConsoleColor.White;
  726. 			Console.Error.Write( "Height" );
  727. 			Console.ResetColor( );
  728. 			Console.Error.WriteLine( "(def: {0}; min: 220; max: screen height)", defaultheight );
  729.  
  730. 			Console.ForegroundColor = ConsoleColor.White;
  731. 			Console.Error.Write( "          /L[:string]" );
  732. 			Console.ResetColor( );
  733. 			Console.Error.Write( " Use " );
  734. 			Console.ForegroundColor = ConsoleColor.White;
  735. 			Console.Error.Write( "L" );
  736. 			Console.ResetColor( );
  737. 			Console.Error.WriteLine( "ocalized or custom captions (see Notes)" );
  738.  
  739. 			Console.ForegroundColor = ConsoleColor.White;
  740. 			Console.Error.Write( "          /N" );
  741. 			Console.ResetColor( );
  742. 			Console.Error.Write( "          list " );
  743. 			Console.ForegroundColor = ConsoleColor.White;
  744. 			Console.Error.Write( "N" );
  745. 			Console.ResetColor( );
  746. 			Console.Error.WriteLine( "etwork printers only (default: list all printers)" );
  747.  
  748. 			Console.ForegroundColor = ConsoleColor.White;
  749. 			Console.Error.Write( "          /O" );
  750. 			Console.ResetColor( );
  751. 			Console.Error.Write( "          list l" );
  752. 			Console.ForegroundColor = ConsoleColor.White;
  753. 			Console.Error.Write( "O" );
  754. 			Console.ResetColor( );
  755. 			Console.Error.WriteLine( "cal printers only   (default: list all printers)" );
  756.  
  757. 			Console.ForegroundColor = ConsoleColor.White;
  758. 			Console.Error.Write( "          /P[:text]" );
  759. 			Console.ResetColor( );
  760. 			Console.Error.Write( "   Alternative \"OK\" button caption \"" );
  761. 			Console.ForegroundColor = ConsoleColor.White;
  762. 			Console.Error.Write( "P" );
  763. 			Console.ResetColor( );
  764. 			Console.Error.Write( "rint\" or \"" );
  765. 			Console.ForegroundColor = ConsoleColor.White;
  766. 			Console.Error.Write( "text" );
  767. 			Console.ResetColor( );
  768. 			Console.Error.WriteLine( "\"" );
  769.  
  770. 			Console.ForegroundColor = ConsoleColor.White;
  771. 			Console.Error.Write( "          /W:width" );
  772. 			Console.ResetColor( );
  773. 			Console.Error.Write( "    window " );
  774. 			Console.ForegroundColor = ConsoleColor.White;
  775. 			Console.Error.Write( "Width" );
  776. 			Console.ResetColor( );
  777. 			Console.Error.WriteLine( " (default: {0}; min: 400; max: screen width)", defaultwidth );
  778.  
  779. 			Console.Error.WriteLine( );
  780.  
  781. 			Console.Error.Write( "Notes:    Use " );
  782. 			Console.ForegroundColor = ConsoleColor.White;
  783. 			Console.Error.Write( "/L" );
  784. 			Console.ResetColor( );
  785. 			Console.Error.Write( " for " );
  786. 			Console.ForegroundColor = ConsoleColor.White;
  787. 			Console.Error.Write( "L" );
  788. 			Console.ResetColor( );
  789. 			Console.Error.WriteLine( "ocalized \"OK\" and \"Cancel\" button captions only." );
  790.  
  791. 			Console.Error.Write( "          Custom captions require a \"localization " );
  792. 			Console.ForegroundColor = ConsoleColor.White;
  793. 			Console.Error.Write( "string" );
  794. 			Console.ResetColor( );
  795. 			Console.Error.WriteLine( "\" in the format" );
  796.  
  797. 			Console.ForegroundColor = ConsoleColor.White;
  798. 			Console.Error.Write( "          /L:\"key=value;key=value;...\"" );
  799. 			Console.ResetColor( );
  800. 			Console.Error.WriteLine( " e.g. for Dutch on English computers:" );
  801.  
  802. 			Console.ForegroundColor = ConsoleColor.White;
  803. 			Console.Error.WriteLine( "          /L:\"Name=Naam;Where=Lokatie;Comment=Opmerking;Cancel=Annuleren\"" );
  804. 			Console.ResetColor( );
  805.  
  806. 			Console.Error.WriteLine( "          The name of the selected printer is written to Standard Out if the" );
  807.  
  808. 			Console.Error.WriteLine( "          \"OK\" button is clicked, otherwise an empty string is returned." );
  809.  
  810. 			Console.Error.Write( "          If \"" );
  811. 			Console.ForegroundColor = ConsoleColor.White;
  812. 			Console.Error.Write( "selected" );
  813. 			Console.ResetColor( );
  814. 			Console.Error.WriteLine( "\" is specified, the program will try an exact (literal)" );
  815.  
  816. 			Console.Error.Write( "          match first; if no match is found, \"" );
  817. 			Console.ForegroundColor = ConsoleColor.White;
  818. 			Console.Error.Write( "selected" );
  819. 			Console.ResetColor( );
  820. 			Console.Error.WriteLine( "\" will be interpreted as" );
  821.  
  822. 			Console.Error.WriteLine( "          a regular expression, and the first match in the sorted printer list" );
  823.  
  824. 			Console.Error.WriteLine( "          will be used." );
  825.  
  826. 			Console.Error.Write( "          If no \"" );
  827. 			Console.ForegroundColor = ConsoleColor.White;
  828. 			Console.Error.Write( "title" );
  829. 			Console.ResetColor( );
  830. 			Console.Error.Write( "\" is specified and " );
  831. 			Console.ForegroundColor = ConsoleColor.White;
  832. 			Console.Error.Write( "/P" );
  833. 			Console.ResetColor( );
  834. 			Console.Error.WriteLine( " is used, the alternative \"OK\"" );
  835.  
  836. 			Console.Error.Write( "          button caption (\"" );
  837. 			Console.ForegroundColor = ConsoleColor.White;
  838. 			Console.Error.Write( "P" );
  839. 			Console.ResetColor( );
  840. 			Console.Error.Write( "rint\" or \"" );
  841. 			Console.ForegroundColor = ConsoleColor.White;
  842. 			Console.Error.Write( "text" );
  843. 			Console.ResetColor( );
  844. 			Console.Error.Write( "\") will be used for \"" );
  845. 			Console.ForegroundColor = ConsoleColor.White;
  846. 			Console.Error.Write( "title" );
  847. 			Console.ResetColor( );
  848. 			Console.Error.WriteLine( "\" too." );
  849.  
  850. 			Console.Error.WriteLine( "          Return code 0 for \"OK\", 1 for (command line) errors, 2 for \"Cancel\"." );
  851.  
  852. 			Console.Error.WriteLine( );
  853.  
  854. 			Console.Error.WriteLine( "Credits:  On-the-fly form based on code by Gorkem Gencay on StackOverflow:" );
  855.  
  856. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  857. 			Console.Error.WriteLine( "          http://stackoverflow.com/questions/97097" );
  858.  
  859. 			Console.Error.WriteLine( "          /what-is-the-c-sharp-version-of-vb-nets-inputdialog#17546909" );
  860. 			Console.ResetColor( );
  861.  
  862. 			Console.Error.WriteLine( "          Code to retrieve localized button captions by Martin Stoeckli:" );
  863.  
  864. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  865. 			Console.Error.WriteLine( "          http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources" );
  866. 			Console.ResetColor( );
  867.  
  868. 			Console.Error.WriteLine( );
  869.  
  870. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  871.  
  872. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  873.  
  874. 			#endregion Show Help Text
  875.  
  876.  
  877. 			return 1;
  878. 		}
  879.  
  880.  
  881. 		#region Get Localized Captions
  882.  
  883. 		// Code to retrieve localized captions by Martin Stoeckli
  884. 		// http://martinstoeckli.ch/csharp/csharp.html#windows_text_resources
  885.  
  886. 		/// <summary>
  887. 		/// Searches for a text resource in a Windows library.
  888. 		/// Sometimes, using the existing Windows resources, you can make your code
  889. 		/// language independent and you don't have to care about translation problems.
  890. 		/// </summary>
  891. 		/// <example>
  892. 		///   btnCancel.Text = Load("user32.dll", 801, "Cancel");
  893. 		///   btnYes.Text = Load("user32.dll", 805, "Yes");
  894. 		/// </example>
  895. 		/// <param name="libraryName">Name of the windows library like "user32.dll"
  896. 		/// or "shell32.dll"</param>
  897. 		/// <param name="ident">Id of the string resource.</param>
  898. 		/// <param name="defaultText">Return this text, if the resource string could
  899. 		/// not be found.</param>
  900. 		/// <returns>Requested string if the resource was found,
  901. 		/// otherwise the <paramref name="defaultText"/></returns>
  902. 		public static string Load( string libraryName, UInt32 ident, string defaultText )
  903. 		{
  904. 			IntPtr libraryHandle = GetModuleHandle( libraryName );
  905. 			if ( libraryHandle != IntPtr.Zero )
  906. 			{
  907. 				StringBuilder sb = new StringBuilder( 1024 );
  908. 				int size = LoadString( libraryHandle, ident, sb, 1024 );
  909. 				if ( size > 0 )
  910. 					return sb.ToString( );
  911. 			}
  912. 			return defaultText;
  913. 		}
  914.  
  915. 		[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
  916. 		private static extern IntPtr GetModuleHandle( string lpModuleName );
  917.  
  918. 		[DllImport( "user32.dll", CharSet = CharSet.Auto )]
  919. 		private static extern int LoadString( IntPtr hInstance, UInt32 uID, StringBuilder lpBuffer, Int32 nBufferMax );
  920.  
  921. 		#endregion Get Localized Captions
  922. 	}
  923.  
  924.  
  925. 	public enum WMIPrinterStatus
  926. 	{
  927. 		Other = 1,
  928. 		Unknown = 2,
  929. 		Idle = 3,
  930. 		Printing = 4,
  931. 		Warmup = 5,
  932. 		StoppedPrinting = 6,
  933. 		Offline = 7,
  934. 		Paused = 8,
  935. 		Error = 9,
  936. 		Busy = 10,
  937. 		NotAvailable = 11,
  938. 		Waiting = 12,
  939. 		Processing = 13,
  940. 		Initialization = 14,
  941. 		PowerSave = 15,
  942. 		PendingDeletion = 16,
  943. 		IOActive = 17,
  944. 		ManualFeed = 18
  945. 	}
  946. }
  947.  

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