通过代码从控制面板获取打印机的打印机首选项

时间:2013-12-25 15:44:34

标签: c# wpf printing

我必须从wpf应用程序将文档打印到任何已安装的打印机。用户可以选择打印机并单击打印按钮。我可以使用所选的打印机打印文档。但是,如果我从控制面板 ex: Pages Per sheetcolor等更改打印机首选项,我将无法获得打印文档的更改打印机首选项。我在代码中使用了printQueueDefaultPrintTicketprintQueue.UserPrintTicket,但两者都只提供默认设置。

如何通过代码始终从控制面板获取打印机的更改printerpreferences而不是默认设置,并在打印时应用这些打印机首选项?

2 个答案:

答案 0 :(得分:2)

这似乎是由WPF打印类中的错误引起的,请参阅: https://social.msdn.microsoft.com/Forums/vstudio/en-US/6ebf6d61-a356-41c3-a444-a24fb38416fe/printticket-not-reflecting-printing-preferences?forum=wpf

作为一种解决方法,您可以使用PrintDialog(不显示)在默认打印机上获取正确的设置,遗憾的是您需要临时更改Windows默认打印机才能获取除其他打印机以外的其他打印机的设置默认的一个。

我写了这个方法,似乎工作得很好。

/// <summary>
///   Get current settings (encapsulated in an PrintTicket) for a specific printer.
/// </summary>
private static PrintTicket GetPrinterSettings(PrintQueue printer)
{
   try
   {
      // Note: Because of a bug in the WPF printing classes
      // this hack is unfortunately necessary in order to get the correct 
      // printer settings. The old/usual method often get the printer
      // standard settings instead of the custom settings. 
      // For more information see:
      // https://social.msdn.microsoft.com/Forums/vstudio/en-US/6ebf6d61-a356-41c3-a444-a24fb38416fe/printticket-not-reflecting-printing-preferences?forum=wpf
      // http://stackoverflow.com/questions/20774420/getting-the-changed-printer-preferences-for-a-printer-from-controlpanel-through

      var printDialog = new System.Windows.Controls.PrintDialog();
      string printerName = printer.FullName;
      string defaultPrinterName = printDialog.PrintQueue.FullName;

      PrintTicket ticket;
      if (defaultPrinterName != printerName)
      {
         // Temporary change default printer in order to get
         // correct printer settings on the specific printer.
         Win32.SetDefaultPrinter(printerName);
         printDialog = new System.Windows.Controls.PrintDialog();
         ticket = printDialog.PrintTicket;
         Win32.SetDefaultPrinter(defaultPrinterName);
      }
      else
         ticket = printDialog.PrintTicket;
      return ticket.Clone();
   }
   catch
   {
      // If the method above fails, use the old method.
      return printer.CurrentJobSettings.CurrentPrintTicket.Clone();
   }
}

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

答案 1 :(得分:0)

PrintDialog中没有任何特定实例可以显示所有打印机首选项。但是您可以使用相应实例中的相应属性获取每个信息。比如printDialog.PrintTicket.PagesPerSheet等。