我是C#
的新手,并且正在使用Windows窗体,Windows 7和.Net 4.0。
我有3台打印机连接到我的计算机,我想在特定打印机上打印Windows测试页。所有打印机名称都列在ComboBox
中,如以下代码所示,我想从ComboBox
中选择一台打印机并打印测试页。
有人知道怎么做吗?
foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
comboBox_Printers.Items.Add(printer);
}
答案 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