windows 如何检测打印机是否已连接?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1617200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect whether a printer is connected or not?
提问by user178222
How to detect the whether a printer is installed in my PC or not and whether the printer connection is active or not?
如何检测我的 PC 中是否安装了打印机以及打印机连接是否处于活动状态?
回答by Martin
This class will list all the printer installed and give you the status of the printer.
此类将列出所有已安装的打印机并为您提供打印机的状态。
using System;
using System.Management;
public class MyClass
{
static void printProps(ManagementObject o,string prop){
try{Console.WriteLine(prop+"|"+o[prop]);}catch(Exception e){Console.Write(e.ToString());}
}
[STAThread]
static void Main(string[] args)
{
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_Printer where Default=True");
string printerName = "";
foreach (ManagementObject printer in searcher.Get()){
printerName = printer["Name"].ToString().ToLower();
Console.WriteLine("Printer :"+printerName);
printProps(printer, "WorkOffline");
//Console.WriteLine();
switch( Int32.Parse( printer["PrinterStatus"].ToString() )){
case 1: Console.WriteLine("Other"); break;
case 2: Console.WriteLine("Unknown");break;
case 3: Console.WriteLine("Idle"); break;
case 4: Console.WriteLine("Printing"); break;
case 5: Console.WriteLine("Warmup"); break;
case 6: Console.WriteLine("Stopped printing"); break;
case 7: Console.WriteLine("Offline"); break;
}
}
}
}
回答by Bruce Chidester
Use the following code and monitor the WorkOffline property. If WorkOffline is True, then it is offline. If it is False, then it is online.
使用以下代码并监视 WorkOffline 属性。如果 WorkOffline 为 True,则它处于脱机状态。如果它是False,那么它是在线的。
static void PrintProps(ManagementObject o, string prop)
{
try { Console.WriteLine(prop + "|" + o[prop]); }
catch (Exception e) { Console.Write(e.ToString()); }
}
static void Main(string[] args)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
foreach (ManagementObject printer in searcher.Get())
{
string printerName = printer["Name"].ToString().ToLower();
Console.WriteLine("Printer :" + printerName);
PrintProps(printer, "Caption");
PrintProps(printer, "ExtendedPrinterStatus");
PrintProps(printer, "Availability");
PrintProps(printer, "Default");
PrintProps(printer, "DetectedErrorState");
PrintProps(printer, "ExtendedDetectedErrorState");
PrintProps(printer, "ExtendedPrinterStatus");
PrintProps(printer, "LastErrorCode");
PrintProps(printer, "PrinterState");
PrintProps(printer, "PrinterStatus");
PrintProps(printer, "Status");
PrintProps(printer, "WorkOffline");
PrintProps(printer, "Local");
}
}