How do I set the windows default printer in C#?

前端 未结 5 1897
抹茶落季
抹茶落季 2020-11-29 06:24

How do I set the windows default printer in C#.NET?

5条回答
  •  孤街浪徒
    2020-11-29 07:01

    This is the method I use now. I include the SetDefaultPrinter method to improve reliability. I derived this from other answers, and it is revised to reflect feedback for my previous answer version.

    Regarding comments: This method is appropriate only inside the scope of a running C# application session. This method does not change printer settings managed by the operating system or stored in the registry.

    using System.Drawing.Printing;
    
    [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool SetDefaultPrinter(string Name);
    
    public static PrinterSettings Printer_Settings = new System.Drawing.Printing.PrinterSettings();
    
    /// 
    /// Get or Sets the session's Default Printer
    /// 
    public static string Session_DefaultPrinter
    {
      get { return Printer_Settings.PrinterName; }
      set
      {
        SetDefaultPrinter(value);
        Printer_Settings.DefaultPageSettings.PrinterSettings.PrinterName = value;
        Printer_Settings.PrinterName = value;
      }
    }
    

    Typical Usage:

    string stashPrinterName = Session_DefaultPrinter;
    // Switch to my Special Printer
    Session_DefaultPrinter = mySpecialPrinter;
    // print to my Special Printer
    // ...
    // Restore the original session's printer
    Session_DefaultPrinter = stashPrinterName;
    

提交回复
热议问题