Determine the default printer in C#

When this example starts, the following event handler fills the cboPrinter ComboBox with the names of the available printers and then 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'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 the PrinterName property 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.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.