C#检查打印机状态

问题描述:

在我的应用程序(Windows 7,VS2010)中,我必须在成功打印图像后减少一个贷记计数器.无论如何,在开始整个过程​​之前,我想了解打印机的状态,以便在出现缺纸,卡纸等情况时提醒用户.现在,环顾四周,我发现了几个使用Windows WMI的示例,但是...永远无法工作.例如,使用代码段,即使我取出纸张,打印机状态也始终处于就绪状态,打开盖子...关闭打印机.

in my application (Windows 7, VS2010) i have to decrement a credit counter after successfully printing an image. Anyway, before starting the entire process, i'd like to know about printer status in order to alert the user on paper out, paper jam and so on. Now, looking around i found several example that use Windows WMI but... never works. Using THIS snippet, for example, the printer status is always ready also if i remove the paper, open the cover... turn off the printer.

现在打印机状态也一直很好,我正在办公室测试正在舒适地在家中关闭的打印机.我要用炸药引爆设备以获取打印机错误状态吗?

The printer status is always good also now, that i'm testing from office the printer that is comfortably turned off at home. have I to detonate the device by dynamite in order to have a printer error status?

这是我使用的代码

ManagementObjectCollection MgmtCollection;
ManagementObjectSearcher MgmtSearcher;

//Perform the search for printers and return the listing as a collection
MgmtSearcher = new ManagementObjectSearcher("Select * from Win32_Printer");
MgmtCollection = MgmtSearcher.Get();

foreach (ManagementObject objWMI in MgmtCollection)
{

    string name = objWMI["Name"].ToString().ToLower();

    if (name.Equals(printerName.ToLower()))
    {

        int state = Int32.Parse(objWMI["ExtendedPrinterStatus"].ToString());
        if ((state == 1) || //Other
        (state == 2) || //Unknown
        (state == 7) || //Offline
        (state == 9) || //error
        (state == 11) //Not Available
        )
        {
        throw new ApplicationException("hope you are finally offline");
        }

        state = Int32.Parse(objWMI["DetectedErrorState"].ToString());
        if (state != 2) //No error
        {
        throw new ApplicationException("hope you are finally offline");
        }

    }

}

在其中接收到"printerName"作为参数的地方.

Where 'printerName' is received as parameter.

谢谢你的建议.

System.Printing 命名空间就是您的追求.它具有许多属性,这些属性提供有关其代表的打印机状态的有用信息.这是一些例子;

The PrintQueue class in the System.Printing namespace is what you are after. It has many properties that give useful information about the status of the printer that it represents. Here are some examples;

        var server = new LocalPrintServer();

        PrintQueue queue = server.DefaultPrintQueue;

        //various properties of printQueue
        var isOffLine = queue.IsOffline;
        var isPaperJam = queue.IsPaperJammed;
        var requiresUser = queue.NeedUserIntervention;
        var hasPaperProblem = queue.HasPaperProblem;
        var isBusy = queue.IsBusy;

这绝不是一个完整的列表,请记住,队列可能具有一个或多个这些状态,因此您必须考虑处理它们的顺序.

This is by no means a comprehensive list and remember that it is possible for the queue to have one or more of these statuses so you'll have to think about the order in which you handle them.