和打印机说话

Vid*_*dar 7 c# printing

有没有办法编写一些可以与打印机"对话"的代码,以便获得有关它状态的一些基本信息?我真正感兴趣的是找出纸张是否已用完或卡纸 - 这种性质的东西.我应该为这类东西使用System.Management库吗?

PS - 知道如何掌握在特定PC上设置的所有打印机也很方便.你会怎么做?

Rob*_*obV 9

使用System.Management从Printers获取信息相对简单.

    //Declare WMI Variables
    ManagementObject MgmtObject;
    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)
    {
       //Do whatever action you want with the Printer
    }
Run Code Online (Sandbox Code Playgroud)

看看http://msdn.microsoft.com/en-us/library/aa394363.aspx的方法和Win32_Printer的性能.对于你的问题:

//Test whether a Win32_Printer is out of paper or jammed
int state = Int32.Parse(objWMI["PrinterState"]);
if (state == 4) {
   //Paper Jam
} else if (state == 5) {
   //Paper Out
}
Run Code Online (Sandbox Code Playgroud)