如何在打印机上打印测试页?

时间:2019-01-31 18:04:47

标签: c# winforms printing

我是C#的新手,并且正在使用Windows窗体,Windows 7和.Net 4.0。 我有3台打印机连接到我的计算机,我想在特定打印机上打印Windows测试页。所有打印机名称都列在ComboBox中,如以下代码所示,我想从ComboBox中选择一台打印机并打印测试页。

我看过HereHereHere,但没有任何帮助。

有人知道怎么做吗?

foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
    comboBox_Printers.Items.Add(printer);
}

1 个答案:

答案 0 :(得分:0)

现在,此方法可能看起来详细,但是我认为在调用WMI方法时,正确定义管理选项和合并范围很重要。
这提供了必要时根据特定上下文更正/适应代码的方法。
另外,此处的辅助方法可以重用于初始化任何其他WMI查询。

例如,错误的 Impersonation 选项将在连接到0x80070005: (E_ACCESSDENIED) WMI时或当连接到Scope WMI时导致异常(PrintTestPage)。 string PrinterName查询被执行。

null 方法参数的说明:

string MachineName :特定打印机的名称或null以使用默认打印机。
LocalMachine :网络中计算机的名称,或使用{strong> 0 名称的var result = PrintTestPage(null, null);

如果成功,则该方法返回using System.Linq; using System.Management; public static uint PrintTestPage(string PrinterName, string MachineName) { ConnectionOptions connOptions = GetConnectionOptions(); EnumerationOptions mOptions = GetEnumerationOptions(false); string machineName = string.IsNullOrEmpty(MachineName) ? Environment.MachineName : MachineName; ManagementScope mScope = new ManagementScope($@"\\{machineName}\root\CIMV2", connOptions); SelectQuery mQuery = new SelectQuery("SELECT * FROM Win32_Printer"); mQuery.QueryString += string.IsNullOrEmpty(PrinterName) ? " WHERE Default = True" : $" WHERE Name = '{PrinterName}'"; mScope.Connect(); using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mScope, mQuery, mOptions)) { ManagementObject moPrinter = moSearcher.Get().OfType<ManagementObject>().FirstOrDefault(); if (moPrinter is null) throw new InvalidOperationException("Printer not found"); InvokeMethodOptions moMethodOpt = new InvokeMethodOptions(null, ManagementOptions.InfiniteTimeout); using (ManagementBaseObject moParams = moPrinter.GetMethodParameters("PrintTestPage")) using (ManagementBaseObject moResult = moPrinter.InvokeMethod("PrintTestPage", moParams, moMethodOpt)) return (UInt32)moResult["ReturnValue"]; } } ,如果未找到打印机,则抛出异常。

使用本地计算机上的默认打印机进行打印测试页的示例调用:

private static EnumerationOptions GetEnumerationOptions(bool DeepScan)
{
    EnumerationOptions mOptions = new EnumerationOptions()
    {
        Rewindable = false,        //Forward only query => no caching
        ReturnImmediately = true,  //Pseudo-async result
        DirectRead = true,         //Skip superclasses
        EnumerateDeep = DeepScan   //No recursion
    };
    return mOptions;
}

private static ConnectionOptions GetConnectionOptions()
{
    ConnectionOptions connOptions = new ConnectionOptions()
    {
        EnablePrivileges = true,
        Timeout = ManagementOptions.InfiniteTimeout,
        Authentication = AuthenticationLevel.PacketPrivacy,
        Impersonation = ImpersonationLevel.Impersonate
    };
    return connOptions;
}

SetTextColor

Helper方法:

DrawText