List all available printers in C#.Net


.Net frame work allows you to enjoy rich set of printing functionalities.  Lets’s learn how to list all printers in a system in C#

Using the PinterSetting class you can access a list of installed printers on your system and can be added to any control you want.

The Printer class belong to the System.Drawing.Printing package, so you need to reference the class by including using System.Drawing.Printing;, at the start of the program module/form.

PrinterSettings setting = new PrinterSettings();
 listBox1.Items.Clear();
 foreach (string prntr in PrinterSettings.InstalledPrinters)
 {
 System.Console.WriteLine(prntr);
 listBox1.Items.Add(prntr);

}

The above mentioned code will add all installed printer names to a list box.

Set Printer as default in C#


As we learned how to list installed printers , also it is possible set printer as default at run time with some tricky C# code. This can be achieved by using winspool.drv functionality.

Firstly incorporate the Winspool functionality to C# by using DllImport.

  1. Add using System.Runtime.InteropServices
  2. Add a public class Myprinter and implement SetDefaultPrinter method (bottom of the namespace )

c#setdefaultprinter

public static class myPrinters
 {
 [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
 public static extern bool SetDefaultPrinter(string Name);

}

Now you can simply set a printer as default using the following code.

myPrinters.SetDefaultPrinter(<yourprinter name>);

 

That is all for today