如何解决将PrintDialog的PrintQueue设置为网络打印机时出错-C#WPF XAML
我试图将WPF PrintDialog设置为使用用户在表单上设置的值来控制基本打印选项,而不会显示对话框。
目标是允许他们一次设置打印选项,然后在一天中数百次使用这些设置,除非他们决定这样做,否则不必更改它们。
该代码适用于本机上安装的除网络打印机以外的所有打印机。如果从列表中选择网络打印机,则会收到以下错误-
System.Printing.PrintQueueException:'填充PrintQueue对象的属性时发生异常。 Win32错误:打印机名称无效。'
奇怪的是,如果我将其中一台网络打印机设置为默认打印机,并添加逻辑以通过将LocalPrintServer.DefaultPrintQueue
传递给PrintDialog
而进行无人看管的打印,则此代码有效。
我已经剖析了打印机名称的处理方式,但我似乎无法弄清楚传入网络打印机的正确方法。
这是我当前的代码(我尝试了多次迭代,结果却完全相同,以至于我输了……大声笑)。
XAML- 我使用以下已安装的打印机列表填充XAML组合框-
<Window x:Class="PrintDialogTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Printing="clr-namespace:System.Printing;assembly=System.Printing"
mc:Ignorable="d"
Title="MainWindow" Height="550" Width="450">
<Window.Resources>
<Printing:LocalPrintServer x:Key="localPrintServer1"/>
<ObjectDataProvider x:Key="printerCollection"
ObjectInstance="{StaticResource localPrintServer1}"
MethodName="GetPrintQueues">
<ObjectDataProvider.MethodParameters>
<x:ArrayExtension Type="{x:Type Printing:EnumeratedPrintQueueTypes}">
<Printing:EnumeratedPrintQueueTypes>Local</Printing:EnumeratedPrintQueueTypes>
<Printing:EnumeratedPrintQueueTypes>Connections</Printing:EnumeratedPrintQueueTypes>
</x:ArrayExtension>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>.............
<ComboBox x:Name="cboPrinters" HorizontalAlignment="Left" Height="34" Margin="53,414,0" VerticalAlignment="Top" Width="354" ItemsSource="{Binding Source={StaticResource printerCollection}}" displayMemberPath="Name" FontSize="14"/>
这工作正常,并为我提供了所有已安装的打印机。
如果我运行该应用程序,然后选择除两台联网打印机以外的任何其他设备,则下面的代码(来自MainWindow.xaml.cs
“打印”按钮的click事件)有效-
// Create a PrintDialog
PrintDialog printDlg = new PrintDialog();
// Create a PrintQueue and PrintServer - assign the user selected printer to the PrintQueue
printDlg.PrintQueue = new PrintQueue(new PrintServer(),cboPrinters.Text);
如前所述,我尝试了多种方法来格式化传递到PrintQueue
的名称值,但没有成功。
PrintServerException - “…name is invalid” even though I can access the path from windows
希望我已经提供了足够的信息,但是如果没有,请告诉我,我将添加所需的其他信息。
任何帮助将不胜感激,并感谢您的任何提前答复。
更新-如果我用网络打印服务器的名称对PrintServer
的实例化进行硬编码,则该代码也适用于网络打印机(需要说明)-
printDlg.PrintQueue = new PrintQueue(new PrintServer(@"\\NetworkPrintServerNameHere"),(string)cboPrinters.SelectedValue);
但是显然,该代码在现实世界中并不实用,因为我们在打印机列表中可以有多个PrintServer
名称。我需要找到一种方法来获取当前所选打印机的PrintServer
名称。
解决方法
因此,使用为组合框创建记录集的请求顶部的代码,我们可以在运行时通过设置以下内容,以编程方式为当前选定的打印机为所需的PrintSever
值解析选定的记录如下-
printDlg.PrintQueue = new PrintQueue(new PrintServer(((System.Printing.PrintQueue)cboPrinters.SelectedItem).HostingPrintServer.Name),(string)cboPrinters.SelectedValue);
我不再遇到错误,可以打印到用户选择的任何本地和网络打印机。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。