如何在wpf中获取默认选择的打印机端口名称

时间:2012-06-15 18:32:34

标签: c# wpf

我编写代码来获取安装在我系统中的打印机名称。但我不知道要获得该打印机端口名称。这里是我写的代码。

public MainWindow()
    {
        this.InitializeComponent();

        PrintServer server = new PrintServer();

        foreach (PrintQueue queue in server.GetPrintQueues())
        {
            cboPrinters.Items.Add(queue.FullName);
        }

        var DefaultPrinter = new LocalPrintServer().DefaultPrintQueue;
        string default_name=DefaultPrinter.FullName;

        txxt_default.Text = "The default printe is "+" "+default_name;
    }

它的结果将是这样的

printer

enter image description here

我必须选择打印机的端口名称“DOP7”(如下图所示)。请帮助我。

1 个答案:

答案 0 :(得分:2)

您是否尝试过PrintQueue.QueuePort Property

string default_port = DefaultPrinter.QueuePort.Name;

<强>更新

然后我建议将PrintQueue对象添加到ComboBox

public MainWindow()
{
   InitializeComponent();

   PrintServer server = new PrintServer();

   foreach (PrintQueue queue in server.GetPrintQueues())
   {
      cboPrinters.Items.Add(queue);
   }
}

并使用DisplayMemberPath展示FullName

<ComboBox Name="cboPrinters"
          DisplayMemberPath="FullName"
          SelectionChanged="cboPrinters_SelectionChanged" />

在EventHandler中,您可以获得如下端口名称:

private void cboPrinters_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   PrintQueue printer = cboPrinters.SelectedItem as PrintQueue;
   string portname = printer.QueuePort.Name;
}