简体   繁体   English

c#打印机属性WMI

[英]c# printer properties WMI

Hello I have this code to retreive printer properties:你好,我有这个代码来检索打印机属性:

string printerName = "PrinterName";
string query = string.Format("SELECT * from Win32_Printer " 
                                + "WHERE Name LIKE '%{0}'",
                             printerName);

ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();

foreach (ManagementObject printer in coll)
{
    foreach (PropertyData property in printer.Properties)
    {
          Console.WriteLine(string.Format("{0}: {1}", 
                                          property.Name, 
                                          property.Value));
    }
}

But properties I need always return the same:但是我需要的属性总是返回相同的:

PrinterState:0打印机状态:0

PrinterStatus:3打印机状态:3

Basically I need this to check if printer is out of paper.基本上我需要这个来检查打印机是否缺纸。 What I think would be: PrinterState: 4我认为会是:PrinterState: 4

Tested on wxp-86 and w7-64 return the same, .Net 4.0在 wxp-86 和 w7-64 上测试返回相同,.Net 4.0

Thank you.谢谢你。

I had this problem as well and there is no easy fix to this.我也遇到了这个问题,对此没有简单的解决方法。

The cause of the problem is that Windows Management Instrumentation (WMI) retrieves the printer information from the spoolsv.exe process.问题的原因是 Windows Management Instrumentation (WMI) 从spoolsv.exe进程中检索打印机信息。 So the reliability of the information retrieved depends completely on the printer driver.因此检索到的信息的可靠性完全取决于打印机驱动程序。 It is likely that the driver of the printer you are querying information for is either bypassing the spooler to get the status or it does not report the status to the spooler process.您正在查询信息的打印机驱动程序很可能绕过假脱机程序来获取状态,或者它没有将状态报告给假脱机程序进程。

Win32_Printer will report whatever status is contained in the spooler. Win32_Printer将报告假脱机程序中包含的任何状态。 So if the spooler reports Ready then it never receives data with a status change as the default is Ready .因此,如果假脱机程序报告Ready则它永远不会收到状态更改的数据,因为默认值为Ready Win32_Printer just exports this as Idle (PrinterStatus = 3 or PrinterState = 0). Win32_Printer只是将其导出为空闲(PrinterStatus = 3 或 PrinterState = 0)。

According to msdn , Paper Out=5根据msdnPaper Out=5

using System;
using System.Management;
using System.Windows.Forms;

namespace WMISample
{
    public class MyWMIQuery
    {
        public static void Main()
        {
            try
            {
                string printerName = "PrinterName";
                ManagementObjectSearcher searcher = 
                    new ManagementObjectSearcher("root\\CIMV2", 
                    "SELECT * FROM Win32_Printer "
                     + "WHERE Name LIKE '%{0}'", printerName);); 

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("Win32_Printer instance");
                    Console.WriteLine("-----------------------------------");
                    Console.WriteLine("PrinterStatus: {0}", queryObj["PrinterStatus"]);
                }
            }
            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }
    }
}

this line:这一行:

string query = string.Format("SELECT * from Win32_Printer " 
                            + "WHERE Name LIKE '%{0}'",
                         printerName);

try call it with % after printername:尝试在打印机名称后使用 % 调用它:

string query = string.Format("SELECT * from Win32_Printer " 
                            + "WHERE Name LIKE '%{0}%'",
                         printerName);

often printer name is: "[printername] On [port]"通常打印机名称是:“[printername] On [port]”

Additionally, you can check extended printer status and another properties;此外,您可以检查扩展打印机状态和其他属性; wired printer can provide more information than wireless printers(Lan, WLan, Bluetooth).有线打印机可以提供比无线打印机(局域网、无线局域网、蓝牙)更多的信息。

https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer

using System;
using System.Management;
using System.Windows.Forms;

namespace PrinterSet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            QueryOnWMI();
        }

        private void QueryOnWMI()
        {
            try
            {
                // Common Information Model v2 (namespace)
                string scope = @"root\CIMV2";
                string printerName = printerNameTextBox.Text.Trim();
                //printerName = "%DocuCentre%";
                string query = "SELECT * FROM Win32_Printer";
                if (!string.IsNullOrEmpty(printerName))
                {
                    query += $" WHERE Name Like '%{printerName}%'";
                }
                Console.Clear();
                var searcher = new ManagementObjectSearcher(scope, query);
                var result = searcher.Get();
                if (result == null || result.Count == 0)
                {
                    Console.WriteLine($"Printer '{printerName}' not found");
                }
                var line = new string('-', 40);
                foreach (ManagementObject queryObj in result)
                {
                    Console.WriteLine(line);
                    Console.WriteLine($"Printer : {queryObj["Name"]}");
                    ushort ps = Convert.ToUInt16(queryObj["PrinterStatus"]);
                    var psEnum = (PrinterStatus)ps;
                    Console.WriteLine("PrinterStatus: {0} ({1})", psEnum, ps);
                    ps = Convert.ToUInt16(queryObj["ExtendedPrinterStatus"]);
                    var psExtended = (ExtendedPrinterStatus)ps;
                    Console.WriteLine("Extended Status: {0} ({1})", psExtended, ps);
                    //var papers = (string[])queryObj["PrinterPaperNames"];
                    //foreach (var paper in papers)
                    //{
                    //    Console.WriteLine("Paper Name: {0}", paper);
                    //}
                    Console.WriteLine(line);
                }
            }
            catch (ManagementException emx)
            {
                // TRY => NET STOP SPOOLER
                // Generic failure is thrown 
                MessageBox.Show(this, "Invalid query: " + emx.Message);
            }
        }

        public enum PrinterStatus : UInt16
        {
            Other = 1, Unknown = 2, Idle = 3, Printing= 4, Warmup = 5, StoppedPrinting = 6, Offline = 7, 
        }

        public enum ExtendedPrinterStatus : UInt16
        {
            Other = 1, Unknown = 2, Idle = 3, Printing, WarmingUp, StoppedPrinting, Offline, Paused, Error, 
            Busy, NotAvailable, Waiting, Processing, Initialization, PowerSave, PendingDeletion, IOActive, ManualFeed

        }

        private void button1_Click(object sender, EventArgs e)
        {
            QueryOnWMI();
        }
    }
}

You can also explore the Windows spooler API: https://docs.microsoft.com/en-us/windows-hardware/drivers/print/introduction-to-spooler-components您还可以探索 Windows spooler API: https : //docs.microsoft.com/en-us/windows-hardware/drivers/print/introduction-to-spooler-components

and this: windows-printer-driver@stackoverflow还有这个: windows-printer-driver@stackoverflow

antonio安东尼奥

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM