using System.Linq; namespace RobvanderWoude { [System.Runtime.InteropServices.Guid( "83C1C4AF-4772-490D-B19D-8306049FB696" )] public interface PrinterSelectBox_Interface { [System.Runtime.InteropServices.DispId( 1 )] void CheckUpdate( ); [System.Runtime.InteropServices.DispId( 2 )] string Credits( ); [System.Runtime.InteropServices.DispId( 3 )] string Help( int html = 0 ); [System.Runtime.InteropServices.DispId( 4 )] string ListAllPrinters( ); [System.Runtime.InteropServices.DispId( 5 )] string ListCategories( ); [System.Runtime.InteropServices.DispId( 6 )] string ListCategory( ); [System.Runtime.InteropServices.DispId( 7 )] string ListProperties( ); [System.Runtime.InteropServices.DispId( 8 )] string SampleCode( ); [System.Runtime.InteropServices.DispId( 9 )] void Show( ); } [System.Runtime.InteropServices.Guid( "1E59AFDD-F2CE-475A-BC3F-8A6AEA4A9B24" ), System.Runtime.InteropServices.InterfaceType( System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIDispatch )] public interface PrinterSelectBox_Events { } [System.Runtime.InteropServices.Guid( "732803C6-23C3-4E19-B231-AF43D946EB5B" ), System.Runtime.InteropServices.ClassInterface( System.Runtime.InteropServices.ClassInterfaceType.AutoDual ), System.Runtime.InteropServices.ComSourceInterfaces( typeof( PrinterSelectBox_Events ) )] public class PrinterSelectBox : PrinterSelectBox_Interface { #region Default Values const string defaultcaptioncancel = "Cancel"; const string defaultcaptionok = "OK"; static readonly System.Drawing.FontFamily defaultfontfamily = System.Drawing.FontFamily.GenericSansSerif; const float defaultfontsize = 10; const PrinterCategory defaultprintercategory = PrinterCategory.All; const int defaulttimeout = 0; static readonly string defaulttitle = string.Format( "{0}, Version {1}", Global.Common.ProgramInfo.FileName, Global.Common.ProgramInfo.FileVersion ); const int defaultwindowheight = 220; const int defaultwindowwidth = 400; const float minimumfontsize = 6; const float maximumfontsize = 48; #endregion Default Values static System.Collections.Generic.List allprinters = QueryPrinters( ); static System.Collections.Generic.List printerslist; #region Controls static System.Windows.Forms.Form printerselectform; static System.Windows.Forms.ComboBox printersdropdown; static System.Windows.Forms.Label statusfield; static System.Windows.Forms.Label typefield; static System.Windows.Forms.Label wherefield; static System.Windows.Forms.Label commentfield; static System.Timers.Timer timer; #endregion Controls #region Methods public void CheckUpdate( ) { Global.Common.ProgramInfo.CheckUpdate( ); } public string Credits( ) { return Global.Common.Credits( ); } static string DefaultPrinter( ) { string defaultprinter = string.Empty; string query = "SELECT * FROM Win32_Printer WHERE Default=TRUE"; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher( "root\\CIMV2", query ); foreach ( System.Management.ManagementObject queryObj in searcher.Get( ) ) { defaultprinter = (string) queryObj["DeviceID"]; } return defaultprinter; } public string Help( int html = 0 ) { int col1width = 0; int col2width = 0; int col3width = 0; int col4width = 0; int col5width = 0; string help = string.Empty; string linetemplate = string.Empty; string separatorline = string.Empty; if ( html == 1 ) { help += "

Help for PrinterSelectBox class

\n\n"; help += "

Present a basic print dialog, and return the selected printer name

\n\n"; help += "

COM ProgID: RobvanderWoude.PrinterSelectBox

\n\n"; } else { help += "Help for PrinterSelectBox class\n"; help += new string( '\u2500', help.Length ) + "\n\n"; help += "Present a basic print dialog, and return the selected printer name\n\n\n"; help += "COM ProgID: RobvanderWoude.PrinterSelectBox\n\n\n"; } #region Properties if ( html == 1 ) { separatorline = string.Empty; linetemplate = "\n\t{0}\n\t{1}\n\t{2}\n\t{3}\n\t{4}\n\n"; help += "\n"; help += "\n"; help += "\t\n"; help += "\n"; help += "\n"; help += "\t\n"; help += "\t\n"; help += "\t\n"; help += "\t\n"; help += "\t\n"; help += "\n"; } else { col1width = 16; col2width = 50; col3width = 9; col4width = 9; col5width = 44; separatorline = "\u251C" + new string( '\u2500', 2 + col1width ) + "\u253C" + new string( '\u2500', 2 + col2width ) + "\u253C" + new string( '\u2500', 2 + col3width ) + "\u253C" + new string( '\u2500', 2 + col4width ) + "\u253C" + new string( '\u2500', 2 + col5width ) + "\u2524\n"; linetemplate = "\u2502 {0,-" + col1width.ToString( ) + "} \u2502 {1,-" + col2width.ToString( ) + "} \u2502 {2,-" + col3width.ToString( ) + "} \u2502 {3,-" + col4width.ToString( ) + "} \u2502 {4,-" + col5width.ToString( ) + "} \u2502\n"; help += "\u250C" + new string( '\u2500', 14 + col1width + col2width + col3width + col4width + col5width ) + "\u2510\n"; help += "\u2502" + new string( ' ', 14 + col1width + col2width + col3width + col4width + col5width ) + "\u2502\n"; help += string.Format( "\u2502 {0,-" + ( 12 + col1width + col2width + col3width + col4width + col5width ).ToString( ) + "} \u2502\n", "Properties (Note that all properties are string or integer, no booleans, objects or arrays)" ); help += "\u2502" + new string( ' ', 14 + col1width + col2width + col3width + col4width + col5width ) + "\u2502\n"; help += "\u255E" + new string( '\u2550', 2 + col1width ) + "\u2564" + new string( '\u2550', 2 + col2width ) + "\u2564" + new string( '\u2550', 2 + col3width ) + "\u2564" + new string( '\u2550', 2 + col4width ) + "\u2564" + new string( '\u2550', 2 + col5width ) + "\u2561\n"; help += string.Format( linetemplate, "Property Name", "Description", "Mandatory", "Read-Only", "Default (Allowed) Values" ); help += "\u255E" + new string( '\u2550', 2 + col1width ) + "\u256A" + new string( '\u2550', 2 + col2width ) + "\u256A" + new string( '\u2550', 2 + col3width ) + "\u256A" + new string( '\u2550', 2 + col4width ) + "\u256A" + new string( '\u2550', 2 + col5width ) + "\u2561\n"; } help += HelpTableRow( linetemplate, "captioncancel", Global.Common.Help.captioncancel, "no", "no", defaultcaptioncancel, html ); help += separatorline; help += HelpTableRow( linetemplate, "captionok", Global.Common.Help.captionok, "no", "no", defaultcaptionok, html ); help += separatorline; help += HelpTableRow( linetemplate, "debuginfo", Global.Common.Help.debuginfo, "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "defaultprinter", "The current default printer name", "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "errors", Global.Common.Help.errors, "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "fontfamily", Global.Common.Help.fontfamily, "no", "no", defaultfontfamily.Name, html ); help += separatorline; help += HelpTableRow( linetemplate, "fontsize", Global.Common.Help.fontsize, "no", "no", string.Format( "{0} ({1}..{2})", defaultfontsize, minimumfontsize, maximumfontsize ), html ); help += separatorline; help += HelpTableRow( linetemplate, "left", Global.Common.Help.left, "no", "no", "Centered (0..screen width - windowwidth)", html ); help += separatorline; help += HelpTableRow( linetemplate, "literal", Global.Common.Help.literal, "no", "no", "0: interpret \"\\t\" as tab and \"\\n\" as newline", html ); help += separatorline; help += HelpTableRow( linetemplate, "localizecaptions", Global.Common.Help.localizecaptions, "no", "no", "0: English captions", html ); help += separatorline; help += HelpTableRow( linetemplate, "modal", Global.Common.Help.modal, "no", "no", "1: always on top", html ); help += separatorline; help += HelpTableRow( linetemplate, "preselected", "The initially preselected printer", "no", "no", "default printer or first in list", html ); help += separatorline; help += HelpTableRow( linetemplate, "printercategory", "Show only printers from this category", "no", "no", string.Format( "{0} ({1})", defaultprintercategory, ListCategories( ).Replace( ";", ", " ) ), html ); help += separatorline; help += HelpTableRow( linetemplate, "selectedprinter", "The printer that was selected when the \"OK\" button was clicked or timeout elapsed; if \"Cancel\" was clicked, selectedprinter is the default printer", "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "timeout", Global.Common.Help.timeout, "no", "no", defaulttimeout.ToString( ), html ); help += separatorline; help += HelpTableRow( linetemplate, "timeoutelapsed", Global.Common.Help.timeoutelapsed, "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "title", Global.Common.Help.title, "no", "no", defaulttitle, html ); help += separatorline; help += HelpTableRow( linetemplate, "top", Global.Common.Help.top, "no", "no", "Centered (0..screen height - windowheight)", html ); help += separatorline; help += HelpTableRow( linetemplate, "Version", Global.Common.Help.version, "N/A", "YES", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "windowheight", Global.Common.Help.windowheight, "no", "no", string.Format( "{0} ({0}..screenheight)", defaultwindowheight ), html ); help += separatorline; help += HelpTableRow( linetemplate, "windowwidth", Global.Common.Help.windowwidth, "no", "no", string.Format( "{0} ({0}..screenwidth)", defaultwindowwidth ), html ); if ( html == 1 ) { help += "
Properties (Note that all properties are string or integer, no booleans, objects or arrays)
Property NameDescriptionMandatoryRead-OnlyDefault (Allowed) Values
\n\n\n"; } else { help += "\u2514" + new string( '\u2500', 2 + col1width ) + "\u2534" + new string( '\u2500', 2 + col2width ) + "\u2534" + new string( '\u2500', 2 + col3width ) + "\u2534" + new string( '\u2500', 2 + col4width ) + "\u2534" + new string( '\u2500', 2 + col5width ) + "\u2518\n\n\n"; } #endregion Properties #region Methods if ( html == 1 ) { separatorline = string.Empty; linetemplate = "\n\t{0}\n\t{1}\n\t{2}\n\n"; help += "\n"; help += "\n"; help += "\t\n"; help += "\n"; help += "\n"; help += "\t\n"; help += "\t\n"; help += "\t\n"; help += "\n"; } else { col1width = 16; col2width = 74; col3width = 44; separatorline = "\u251C" + new string( '\u2500', 2 + col1width ) + "\u253C" + new string( '\u2500', 2 + col2width ) + "\u253C" + new string( '\u2500', 2 + col3width ) + "\u2524\n"; linetemplate = "\u2502 {0,-" + col1width.ToString( ) + "} \u2502 {1,-" + col2width.ToString( ) + "} \u2502 {2,-" + col3width.ToString( ) + "} \u2502\n"; help += "\u250C" + new string( '\u2500', 8 + col1width + col2width + col3width ) + "\u2510\n"; help += "\u2502" + new string( ' ', 8 + col1width + col2width + col3width ) + "\u2502\n"; help += string.Format( "\u2502 {0,-" + ( 6 + col1width + col2width + col3width ).ToString( ) + "} \u2502\n", "Methods" ); help += "\u2502" + new string( ' ', 8 + col1width + col2width + col3width ) + "\u2502\n"; help += "\u255E" + new string( '\u2550', 2 + col1width ) + "\u2564" + new string( '\u2550', 2 + col2width ) + "\u2564" + new string( '\u2550', 2 + col3width ) + "\u2561\n"; help += string.Format( linetemplate, "Method Name", "Description", "Requirements" ); help += "\u255E" + new string( '\u2550', 2 + col1width ) + "\u256A" + new string( '\u2550', 2 + col2width ) + "\u256A" + new string( '\u2550', 2 + col3width ) + "\u2561\n"; } help += HelpTableRow( linetemplate, "CheckUpdate", Global.Common.Help._checkupdate, "", html ); help += separatorline; help += HelpTableRow( linetemplate, "Credits", Global.Common.Help._credits, "", html ); help += separatorline; help += HelpTableRow( linetemplate, "Help", Global.Common.Help._help, "", html ); help += separatorline; help += HelpTableRow( linetemplate, "ListAllPrinters", "Returns as list of all printers", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "ListCategories", "Returns as list of available printer categories", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "ListCategory", "Returns as list of all printers in the selected category", "", html ); help += separatorline; help += HelpTableRow( linetemplate, "ListProperties", Global.Common.Help._listproperties, "", html ); help += separatorline; help += HelpTableRow( linetemplate, "SampleCode", Global.Common.Help._samplecode, "", html ); help += separatorline; help += HelpTableRow( linetemplate, "Show", "Presents a basic print dialog based on the current property values, and if \"OK\" is clicked, saves last selected printer name in the \"selectedprinter\" property (if \"Cancel\" is clicked, \"selectedprinter\" is default printer).", "", html ); if ( html == 1 ) { help += "
Methods
Method NameDescriptionRequirements
\n\n\n"; } else { help += "\u2514" + new string( '\u2500', 2 + col1width ) + "\u2534" + new string( '\u2500', 2 + col2width ) + "\u2534" + new string( '\u2500', 2 + col3width ) + "\u2518\n\n\n"; } #endregion Methods #region Example if ( html == 1 ) { help += "

VBScript usage example:

\n\n
";
			}
			else
			{
				help += "VBScript usage example:\n";
				help += new string( '\u2500', 23 ) + "\n\n";
			}

			help += SampleCode( );

			if ( html == 1 )
			{
				help += "
"; } help += "\n\n"; #endregion Example help = help.Replace( "\n", System.Environment.NewLine ); return help; } private string HelpTableRow( string template, string col1text, string col2text, string col3text, int html ) { if ( html == 1 ) { return Global.Common.Help.HelpTableRowHTML( col1text, col2text, col3text ); } else { return Global.Common.Help.HelpTableRowText( template, col1text, col2text, col3text, "", "" ); } } private string HelpTableRow( string template, string col1text, string col2text, string col3text, string col4text, string col5text, int html ) { if ( html == 1 ) { return Global.Common.Help.HelpTableRowHTML( col1text, col2text, col3text, col4text, col5text ); } else { return Global.Common.Help.HelpTableRowText( template, col1text, col2text, col3text, col4text, col5text ); } } public string ListAllPrinters( ) { return string.Join( ";", allprinters.Select( p => p[0] ).ToArray( ) ); } public string ListCategories( ) { return string.Join( ";", System.Enum.GetNames( typeof( PrinterCategory ) ) ); } public string ListCategory( ) { return string.Join( ";", printerslist.Select( p => p[0] ).ToArray( ) ); } public string ListProperties( ) { return Global.Common.Lists.Properties( this ); } static System.Collections.Generic.List QueryPrinters( ) { System.Collections.Generic.List printers = new System.Collections.Generic.List( ); string query = "SELECT * FROM Win32_Printer"; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher( "root\\CIMV2", query ); foreach ( System.Management.ManagementObject queryObj in searcher.Get( ) ) { string printer = (string) queryObj["DeviceID"]; uint printerstatus = System.Convert.ToUInt32( queryObj["ExtendedPrinterStatus"] ); string printertype = (string) queryObj["DriverName"]; string printerlocation = (string) queryObj["Location"]; string printerport = (string) queryObj["PortName"]; string printercomment = (string) queryObj["Comment"]; bool isdefault = (bool) queryObj["Default"]; bool islocal = (bool) queryObj["Local"]; bool isnetwork = (bool) queryObj["Network"]; bool isphysical = ( queryObj["PrintProcessor"].ToString( ).ToLower( ) != "winprint" ); string[] printerproperties = new string[9]; printerproperties[0] = printer; printerproperties[1] = ( (WMIPrinterStatus) printerstatus ).ToString( ); printerproperties[2] = printertype; if ( string.IsNullOrWhiteSpace( printerlocation ) ) { printerproperties[3] = printerport; } else { printerproperties[3] = printerlocation; } printerproperties[4] = printercomment; printerproperties[5] = ( isdefault ? "1" : "0" ); printerproperties[6] = ( islocal ? "1" : "0" ); printerproperties[7] = ( isnetwork ? "1" : "0" ); printerproperties[8] = ( isphysical ? "1" : "0" ); printers.Add( printerproperties ); } printers.Sort( ( x, y ) => string.Compare( x[0], y[0] ) ); return printers; } public string SampleCode( ) { string code = "Set objPrinterSelectBox = CreateObject( \"RobvanderWoude.PrinterSelectBox\" )\n\n"; code += "With objPrinterSelectBox\n"; code += "\t.printercategory = \"Physical\"\n"; code += "\t.top = 200\n"; code += "\t.left = 300\n"; code += "\t.timeout = 15\n"; code += "\t.title = \"Select a Physical Printer\"\n"; code += "\tWScript.Echo\n"; code += "\tWScript.Echo \"Printers to choose from:\"\n"; code += "\tWScript.Echo \"========================\"\n"; code += "\tWScript.Echo .ListCategory( )\n"; code += "\tWScript.Echo\n"; code += "\t.Show\n"; code += "\tWScript.Echo \"Selected printer: \" & .selectedprinter\n"; code += "\tWScript.Echo\n"; code += "\tWScript.Echo \"Default printer: \" & .defaultprinter\n"; code += "\tWScript.Echo\n"; code += "\tWScript.Echo .ListProperties( )\n"; code += "End With\n\n"; code += "Set objPrinterSelectBox = Nothing"; return code; } [System.STAThread] public void Show( ) { #region Check Printers List if ( printerslist.Count == 0 ) { _debuginfo.Add( string.Format( "{0}Printers list for category \"{1}\" is empty, using category \"All\" with {2} printers instead", timestamp, printercategory, allprinters.Count ) ); printerslist = allprinters; _printercategory = PrinterCategory.All; } #endregion Check Printers List #region Timer _timeoutelapsed = false; if ( timeout > 0 ) { timer = new System.Timers.Timer( ); timer.Elapsed += new System.Timers.ElapsedEventHandler( PrinterSelectBox_Timer_Elapsed ); timer.Interval = timeout * 1000; timer.Start( ); _debuginfo.Add( timestamp + "Timer started with interval " + timeout.ToString( ) ); } #endregion Timer #region Build Form try { #region Form printerselectform = new System.Windows.Forms.Form( ); System.Drawing.Size size = new System.Drawing.Size( windowwidth, windowheight ); printerselectform.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; printerselectform.MaximizeBox = false; printerselectform.MinimizeBox = false; printerselectform.ClientSize = size; printerselectform.Text = title; printerselectform.Font = new System.Drawing.Font( fontfamily, fontsize ); printerselectform.TopLevel = topmost; if ( left < 0 || top < 0 ) { printerselectform.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; } else { printerselectform.StartPosition = System.Windows.Forms.FormStartPosition.Manual; printerselectform.Location = new System.Drawing.Point( left, top ); } _debuginfo.Add( timestamp + "Window width: " + windowwidth ); _debuginfo.Add( timestamp + "Window height: " + windowheight ); _debuginfo.Add( timestamp + "Window location: " + printerselectform.Location.X + "," + printerselectform.Location.Y ); #endregion Form #region Label 'Name' System.Windows.Forms.Label labelName = new System.Windows.Forms.Label( ); labelName.Size = new System.Drawing.Size( 70, 20 ); labelName.Location = new System.Drawing.Point( 10, 27 ); labelName.Text = "Name:"; printerselectform.Controls.Add( labelName ); #endregion Label 'Name' #region Dropdown printersdropdown = new System.Windows.Forms.ComboBox( ); printersdropdown.Size = new System.Drawing.Size( size.Width - 100, 25 ); printersdropdown.Location = new System.Drawing.Point( 90, 25 ); printersdropdown.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append; printersdropdown.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; printersdropdown.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; foreach ( string[] printer in printerslist ) { printersdropdown.Items.Add( printer[0] ); } printersdropdown.Update( ); printersdropdown.SelectedIndex = _preselectedindex; printersdropdown.SelectedIndexChanged += new System.EventHandler( PrinterSelectBox_Combobox_SelectedIndexChanged ); printerselectform.Controls.Add( printersdropdown ); #endregion Dropdown #region Label 'Status' System.Windows.Forms.Label labelStatus = new System.Windows.Forms.Label( ); labelStatus.Size = new System.Drawing.Size( 70, 20 ); labelStatus.Location = new System.Drawing.Point( 10, 57 ); labelStatus.Text = "Status:"; printerselectform.Controls.Add( labelStatus ); #endregion Label 'Status' #region Printer Status Field statusfield = new System.Windows.Forms.Label( ); statusfield.Size = new System.Drawing.Size( size.Width - 10 - 80, 20 ); statusfield.Location = new System.Drawing.Point( 90, 57 ); statusfield.Text = "Status Value"; printerselectform.Controls.Add( statusfield ); #endregion Printer Status Field #region Label 'Type' System.Windows.Forms.Label labelType = new System.Windows.Forms.Label( ); labelType.Size = new System.Drawing.Size( 70, 20 ); labelType.Location = new System.Drawing.Point( 10, 82 ); labelType.Text = "Type:"; printerselectform.Controls.Add( labelType ); #endregion Label 'Type' #region Printer Type Description typefield = new System.Windows.Forms.Label( ); typefield.Size = new System.Drawing.Size( size.Width - 10 - 80, 20 ); typefield.Location = new System.Drawing.Point( 90, 82 ); typefield.Text = "Type Value"; printerselectform.Controls.Add( typefield ); #endregion Printer Type Description #region Label 'Where' System.Windows.Forms.Label labelWhere = new System.Windows.Forms.Label( ); labelWhere.Size = new System.Drawing.Size( 70, 20 ); labelWhere.Location = new System.Drawing.Point( 10, 107 ); labelWhere.Text = "Where:"; printerselectform.Controls.Add( labelWhere ); #endregion Label 'Where' #region Printer Location Field wherefield = new System.Windows.Forms.Label( ); wherefield.Size = new System.Drawing.Size( size.Width - 10 - 80, 20 ); wherefield.Location = new System.Drawing.Point( 90, 107 ); wherefield.Text = "Where Value"; printerselectform.Controls.Add( wherefield ); #endregion Printer Location Field #region Label 'Comment' System.Windows.Forms.Label labelComment = new System.Windows.Forms.Label( ); labelComment.Size = new System.Drawing.Size( 70, 20 ); labelComment.Location = new System.Drawing.Point( 10, 132 ); labelComment.Text = "Comment:"; printerselectform.Controls.Add( labelComment ); #endregion Label 'Comment' #region Comment Field commentfield = new System.Windows.Forms.Label( ); commentfield.Size = new System.Drawing.Size( size.Width - 10 - 80, 20 ); commentfield.Location = new System.Drawing.Point( 90, 132 ); commentfield.Text = "Comment Value"; printerselectform.Controls.Add( commentfield ); #endregion Comment Field #region Buttons System.Windows.Forms.Button okButton = new System.Windows.Forms.Button( ); okButton.DialogResult = System.Windows.Forms.DialogResult.OK; okButton.Name = "okButton"; okButton.Size = new System.Drawing.Size( 80, 25 ); okButton.Text = captionok; okButton.Location = new System.Drawing.Point( size.Width / 2 - 10 - 80, 175 ); printerselectform.Controls.Add( okButton ); System.Windows.Forms.Button cancelButton = new System.Windows.Forms.Button( ); cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; cancelButton.Name = "cancelButton"; cancelButton.Size = new System.Drawing.Size( 80, 25 ); cancelButton.Text = captioncancel; cancelButton.Location = new System.Drawing.Point( size.Width / 2 + 10, 175 ); printerselectform.Controls.Add( cancelButton ); #endregion Buttons statusfield.Text = printerslist[_preselectedindex][1]; typefield.Text = printerslist[_preselectedindex][2]; wherefield.Text = printerslist[_preselectedindex][3]; commentfield.Text = printerslist[_preselectedindex][4]; printerselectform.AcceptButton = okButton; // OK on Enter printerselectform.CancelButton = cancelButton; // Cancel on Esc printerselectform.Activate( ); } catch ( System.Exception e ) { _errors.Add( Global.Common.TimeStamp( ) + "Error while trying to build form: " + e.Message ); } #endregion Build Form #region Show Dialog and Return Result try { System.Windows.Forms.DialogResult result = printerselectform.ShowDialog( ); if ( _timeoutelapsed ) { _debuginfo.Add( timestamp + "Timeout elapsed" ); } else if ( result == System.Windows.Forms.DialogResult.Cancel ) { _debuginfo.Add( timestamp + "Cancelled, using default printer" ); _selectedprinter = defaultprinter; } else // OK { _selectedprinter = printersdropdown.Text; } _debuginfo.Add( timestamp + "Selected printer: " + selectedprinter ); } catch ( System.Exception e ) { _errors.Add( Global.Common.TimeStamp( ) + "Error while trying to show dialog: " + e.Message ); } #endregion Show Dialog and Return Result } public void UpdatePrinterSelectBoxFields( ) { try { string printername = printersdropdown.Text; statusfield.Text = printerslist.Where( p => p[0] == printername ).First( )[1]; typefield.Text = printerslist.Where( p => p[0] == printername ).First( )[2]; wherefield.Text = printerslist.Where( p => p[0] == printername ).First( )[3]; commentfield.Text = printerslist.Where( p => p[0] == printername ).First( )[4]; } catch ( System.Exception e ) { _errors.Add( Global.Common.TimeStamp( ) + "Error updating dialog fields: " + e.Message ); } } #endregion Methods #region Properties private string _captioncancel = defaultcaptioncancel; [System.Runtime.InteropServices.ComVisible( true )] public string captioncancel { get { if ( _localizecaptions && _captioncancel == defaultcaptioncancel ) { _captioncancel = Global.Common.Localization.Load( "user32.dll", 801, defaultcaptioncancel ); } return _captioncancel; } set { if ( string.IsNullOrWhiteSpace( value ) || value.Length > 20 ) { _captioncancel = defaultcaptioncancel; } else { _captioncancel = value; } //_debuginfo.Add() } } private string _captionok = defaultcaptionok; [System.Runtime.InteropServices.ComVisible( true )] public string captionok { get { if ( _localizecaptions && _captionok == defaultcaptionok ) { _captionok = Global.Common.Localization.Load( "user32.dll", 800, defaultcaptionok ); } return _captionok; } set { if ( string.IsNullOrWhiteSpace( value ) || value.Length > 20 ) { _captionok = defaultcaptionok; } else { _captionok = value; } } } private System.Collections.Generic.List _debuginfo = new System.Collections.Generic.List( ); [System.Runtime.InteropServices.ComVisible( true )] public string debuginfo { get { return string.Join( "\n", _debuginfo.ToArray( ) ); } } private string _defaultprinter = DefaultPrinter( ); [System.Runtime.InteropServices.ComVisible( true )] public string defaultprinter { get { return _defaultprinter; } } private System.Collections.Generic.List _errors = new System.Collections.Generic.List( ); [System.Runtime.InteropServices.ComVisible( true )] public string errors { get { return string.Join( "\n", _errors.ToArray( ) ); } } private System.Drawing.FontFamily _fontfamily = defaultfontfamily; [System.Runtime.InteropServices.ComVisible( true )] public string fontfamily { get { return _fontfamily.Name; } set { _fontfamily = Global.Common.Validate.FontFamily( value, defaultfontfamily ); } } private float _fontsize = defaultfontsize; [System.Runtime.InteropServices.ComVisible( true )] public int fontsize { get { return System.Convert.ToInt32( _fontsize ); } set { _fontsize = System.Convert.ToSingle( value ).LimitToRange( minimumfontsize, maximumfontsize ); } } private int _left = -1; [System.Runtime.InteropServices.ComVisible( true )] public int left { get { return _left; } set { if ( value < -1 ) { _left = 0; } else if ( value > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width - windowwidth ) { _left = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width - windowwidth; } else { _left = value; } } } private bool _literal = false; [System.Runtime.InteropServices.ComVisible( true )] public int literal { get { return ( _literal ? 1 : 0 ); } set { _literal = ( value == 1 ); } } private bool _localizecaptions = false; [System.Runtime.InteropServices.ComVisible( true )] public int localizecaptions { get { return ( _localizecaptions ? 1 : 0 ); } set { _localizecaptions = ( value == 1 ); } } private bool topmost = true; [System.Runtime.InteropServices.ComVisible( true )] public int modal { get { return ( topmost ? 1 : 0 ); } set { topmost = ( value == 1 ); } } private int _preselectedindex = allprinters.Select( p => p[0] ).ToList( ).IndexOf( DefaultPrinter( ) ); [System.Runtime.InteropServices.ComVisible( true )] public string preselected { get { return printerslist[_preselectedindex][0]; } set { if ( int.TryParse( value, out _preselectedindex ) ) { _debuginfo.Add( timestamp + "Preselected is numeric, trying to use it as index" ); if ( _preselectedindex < 0 ) { _debuginfo.Add( timestamp + "Preselected < 0, using index 0 instead" ); _preselectedindex = 0; } if ( _preselectedindex >= printerslist.Count ) { _debuginfo.Add( timestamp + "Preselected > printers count, using index 0 instead" ); _preselectedindex = 0; } else { _debuginfo.Add( timestamp + "Preselected is a valid index" ); } } else { _debuginfo.Add( timestamp + "Preselected: " + value ); if ( printerslist.Select( p => p[0] ).ToList( ).Contains( value ) ) // first check for full printer name match { _debuginfo.Add( timestamp + "Full printer name match" ); _preselectedindex = printerslist.FindIndex( p => p[0].Equals( value, System.StringComparison.InvariantCultureIgnoreCase ) ); } else if ( printerslist.Where( p => p[0].ToUpper( ).StartsWith( value.ToUpper( ) ) ).Any( ) ) // if not, try a partial printer name match at begin of the name { _debuginfo.Add( timestamp + "Partial printer name match (startswith)" ); _preselectedindex = printerslist.FindIndex( p => p[0].ToUpper( ).StartsWith( value.ToUpper( ) ) ); } else if ( printerslist.Where( p => p[0].ToUpper( ).Contains( value.ToUpper( ) ) ).Any( ) ) // if not, try a partial printer name match anywhere in the name { _debuginfo.Add( timestamp + "Partial printer name match (anywhere)" ); _preselectedindex = printerslist.FindIndex( p => p[0].ToUpper( ).Contains( value.ToUpper( ) ) ); } else if ( printerslist.Select( p => p[2] ).ToList( ).Contains( value ) ) // if not, check for full driver name match { _debuginfo.Add( timestamp + "Full driver name match" ); _preselectedindex = printerslist.FindIndex( p => p[2].Equals( value, System.StringComparison.InvariantCultureIgnoreCase ) ); } else if ( printerslist.Where( p => p[2].ToUpper( ).StartsWith( value.ToUpper( ) ) ).Any( ) ) // if not, try a partial driver name match at begin of the name { _debuginfo.Add( timestamp + "Partial driver name match (startswith)" ); _preselectedindex = printerslist.FindIndex( p => p[2].ToUpper( ).StartsWith( value.ToUpper( ) ) ); } else if ( printerslist.Where( p => p[2].ToUpper( ).Contains( value.ToUpper( ) ) ).Any( ) ) // if not, try a partial driver name match anywhere in the name { _debuginfo.Add( timestamp + "Partial driver name match (anywhere)" ); _preselectedindex = printerslist.FindIndex( p => p[2].ToUpper( ).Contains( value.ToUpper( ) ) ); } else // or just stick with the first printer in the list { _debuginfo.Add( timestamp + "No match, using index 0" ); _preselectedindex = 0; } } _debuginfo.Add( timestamp + "Preselected printer: " + preselected ); } } private static PrinterCategory _printercategory = defaultprintercategory; [System.Runtime.InteropServices.ComVisible( true )] public string printercategory { get { return _printercategory.ToString( ); } set { _debuginfo.Add( timestamp + "Trying to match \"" + value + "\" to a printer category" ); if ( System.Enum.TryParse( value, true, out PrinterCategory category ) ) { switch ( category ) { case PrinterCategory.All: _printercategory = PrinterCategory.All; printerslist = allprinters; break; case PrinterCategory.Local: _printercategory = PrinterCategory.Local; printerslist = allprinters.Where( p => p[6] == "1" ).ToList( ); break; case PrinterCategory.Network: _printercategory = PrinterCategory.Network; printerslist = allprinters.Where( p => p[7] == "1" ).ToList( ); break; case PrinterCategory.Physical: _printercategory = PrinterCategory.Physical; printerslist = allprinters.Where( p => p[8] == "1" ).ToList( ); break; case PrinterCategory.Virtual: _printercategory = PrinterCategory.Virtual; printerslist = allprinters.Where( p => p[8] == "0" ).ToList( ); break; default: _debuginfo.Add( timestamp + "Printer category not recognized, assuming All" ); _errors.Add( Global.Common.TimeStamp( ) + "Printer category not recognized, assuming All" ); _printercategory = PrinterCategory.All; printerslist = allprinters; break; } _debuginfo.Add( timestamp + "Printer category: " + _printercategory.ToString( ) ); _debuginfo.Add( timestamp + "Number of printers in category " + printercategory + ": " + printerslist.Count ); } else { _debuginfo.Add( timestamp + "Invalid printer category, assuming All" ); _errors.Add( Global.Common.TimeStamp( ) + "Invalid printer category, assuming All" ); _printercategory = PrinterCategory.All; printerslist = allprinters; } if ( printerslist.Count == 0 ) { _debuginfo.Add( timestamp + "No matching printers found in category " + _printercategory.ToString( ) ); _errors.Add( Global.Common.TimeStamp( ) + "No matching printers found in category " + _printercategory.ToString( ) ); } } } private static string _selectedprinter = string.Empty; [System.Runtime.InteropServices.ComVisible( true )] public string selectedprinter { get { return _selectedprinter; } } private int _timeout = defaulttimeout; [System.Runtime.InteropServices.ComVisible( true )] public int timeout { get { return _timeout; } set { if ( value < 0 || value > 3600 ) { _timeout = 0; } else { _timeout = value; } } } private bool _timeoutelapsed = false; [System.Runtime.InteropServices.ComVisible( true )] public int timeoutelapsed { get { return ( _timeoutelapsed ? 1 : 0 ); } } public static string timestamp => Global.Common.TimeStamp( ); private string _title = defaulttitle; [System.Runtime.InteropServices.ComVisible( true )] public string title { get { return _title; } set { if ( string.IsNullOrWhiteSpace( value ) ) { _title = string.Format( "{0}, Version {1}", Global.Common.ProgramInfo.FileName, Global.Common.ProgramInfo.FileVersion ); } else { _title = value.Trim( ); } } } private int _top = -1; [System.Runtime.InteropServices.ComVisible( true )] public int top { get { return _top; } set { if ( value < -1 ) { _top = 0; } else if ( value > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height - windowheight ) { _top = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height - windowheight; } else { _top = value; } } } [System.Runtime.InteropServices.ComVisible( true )] public string Version { get { return Global.Common.ProgramInfo.FileVersion; } } private int _windowheight = defaultwindowheight; [System.Runtime.InteropServices.ComVisible( true )] public int windowheight { get { return _windowheight; } set { if ( value < defaultwindowheight ) { _windowheight = defaultwindowheight; } else if ( value > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height ) { _windowheight = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height; } else { _windowheight = value; } } } private int _windowwidth = defaultwindowwidth; [System.Runtime.InteropServices.ComVisible( true )] public int windowwidth { get { return _windowwidth; } set { if ( value < defaultwindowwidth ) { _windowwidth = defaultwindowwidth; } else if ( value > System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width ) { _windowwidth = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width; } else { _windowwidth = value; } } } #endregion Properties #region Event Handlers private void PrinterSelectBox_Combobox_SelectedIndexChanged( object sender, System.EventArgs e ) { _selectedprinter = printersdropdown.Text; UpdatePrinterSelectBoxFields( ); } private void PrinterSelectBox_Timer_Elapsed( object sender, System.Timers.ElapsedEventArgs e ) { _timeoutelapsed = true; _selectedprinter = printersdropdown.Text; printerselectform.Close( ); } #endregion Event Handlers } }