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

bwntbbo3  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(213)

我是C#的新手,我正在使用windows窗体、windows 7和.Net 4.0。我有3台打印机连接到我的计算机。我想在特定的打印机上打印windows测试页。所有打印机名称都列在ComboBox中,如以下代码所示。我想从ComboBox中选择一台打印机并打印测试页。
我看了看这里,HereHere,但没有任何帮助。
有人知道怎么做吗?

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

rvpgvaaj1#

现在,这个方法可能看起来 * 冗长 ,但我认为在调用WMI方法时,正确定义管理选项和作用域是很重要的。
这提供了在必要时纠正/调整代码以适应特定上下文的方法。
此外,这里的helper方法还可以重用来初始化任何其他WMI查询。
例如,当连接到WMIScope或执行WMI查询时,错误的
*Impersonation**选项将导致异常(0x80070005: (E_ACCESSDENIED))。

**PrintTestPage方法参数的说明:
string PrinterName:指定打印机的名称,或null以使用默认打印机。
string MachineName:网络中计算机的名称或null以使用
LocalMachine**名称。

如果成功,该方法将返回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;
}

相关问题