【问题标题】:Getting the changed printer preferences for a printer from controlpanel through code通过代码从控制面板获取打印机的更改打印机首选项
【发布时间】:2026-02-20 12:30:01
【问题描述】:

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

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

【问题讨论】:

  • 您是否在应用程序中使用过 PrintDialog 实例?
  • 是的,我正在使用应用程序中的 PrintDialog 实例来调用打印功能而不显示打印对话框。
  • @bhanupriyat 我也遇到了同样的问题,你解决了吗?

标签: c# wpf printing


【解决方案1】:

这似乎是由 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://*.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);
}

【讨论】:

  • @yavor87 很高兴它有帮助:-)
【解决方案2】:

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

【讨论】:

    最近更新 更多