美文网首页
C#使用WMI获取打印机以及作业列表

C#使用WMI获取打印机以及作业列表

作者: xmsec | 来源:发表于2016-07-14 22:43 被阅读0次
    • 获取打印机列表
    public static StringCollection GetPrintersCollection()
            {
                StringCollection printerNameCollection = new StringCollection();
                string searchQuery = "SELECT * FROM Win32_Printer";
             ManagementObjectSearcher searchPrinters =  
                new ManagementObjectSearcher(searchQuery);  //exec WQL
             ManagementObjectCollection printerCollection = 
                searchPrinters.Get();  // get a set of object of managementobject            
             foreach (ManagementObject printer in printerCollection)
                {
                if ((bool)printer.GetPropertyValue("default") == true)  
                    //judge if the current print is the default printer 
                    {
                      DefaultPrinterName = printer.Properties["Name"].Value.ToString();                                        
                    }  
                 printerNameCollection. Add(printer.Properties["Name"].Value.ToString());  
    //add to the string set                
                }
                    return printerNameCollection;            
            }
    
    • 获取作业列表
    public static StringCollection GetPrintJobsCollection(string printerName)
            {
                StringCollection printJobCollection = new StringCollection();
                string searchQuery = "SELECT * FROM Win32_PrintJob";
                /*searchQuery can also be mentioned with where Attribute,
                    but this is not working in Windows 2000 / ME / 98 machines 
                    and throws Invalid query error*/
                ManagementObjectSearcher searchPrintJobs =
                          new ManagementObjectSearcher(searchQuery);
                ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
                foreach (ManagementObject prntJob in prntJobCollection)
                {
                    System.String jobName = prntJob.Properties["Name"].Value.ToString();               
                    //Job name would be of the format [Printer name], [Job ID]
                    char[] splitArr = new char[1];
                    splitArr[0] = Convert.ToChar(",");
                    string prnterName = jobName.Split(splitArr)[0];
                    string documentName = prntJob.Properties["Document"].Value.ToString();
                    if (String.Compare(prnterName, printerName, true) == 0)
                    {
                        printJobCollection.Add(documentName);
                    }
                }
                return printJobCollection;
            }
    

    相关文章

      网友评论

          本文标题:C#使用WMI获取打印机以及作业列表

          本文链接:https://www.haomeiwen.com/subject/vwfyjttx.html