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

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