Title: Determine the default printer in C#
When this example starts, the following code lists the printers and selects the default printer.
private void Form1_Load(object sender, EventArgs e)
{
// Find all of the installed printers.
foreach (string printer in PrinterSettings.InstalledPrinters)
{
cboPrinter.Items.Add(printer);
}
// Find and select the default printer.
try
{
PrinterSettings settings = new PrinterSettings();
cboPrinter.Text = settings.PrinterName;
}
catch
{
}
}
The code first loops through the PrinterSettings.InstalledPrinters string collection and adds the printers to the cboPrinter ComboBox. (PrinterSettings is defined in the System.Drawing.Printing namespace.)
Next the code gets an object representing the PrinterSettings. That object is initialized with default printing values. In particular, its PrinterName property gives the name of the default printer. The code sets the ComboBox control's Text property to that printer's name.
There are two weird things here. First, the PrinterSettings class's InstalledPrinters property is a static (shared) property so you need to use the class's name to use it. You cannot creates the settings object and then use its InstalledPrinters property.
Second, properties such as PrinterName are instance values so you need to create an instance of the PrinterSettings class to use them.
(It would have been more consistent if all of the values were either static or instance values. I suspect Microsoft did it this way because a program can set the instance values to change the defaults but it cannot set values in the InstalledPrinters collection to change the available printers. I guess that makes sense. Static values are fixed and instance values are changeable.)
Download the example to experiment with it and to see additional details.
|