C#使用WMI设置和获取默认打印机

2016-07-14  本文已影响0人  xmsec
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
protected int SetDefaultPrinter(string PrinterName)  
{  
        int reint = 0;    
        ManagementObjectSearcher query;  
        ManagementObjectCollection queryCollection;  
        string _classname = "SELECT * FROM Win32_Printer";  
        query = new ManagementObjectSearcher(_classname);  
        queryCollection = query.Get();  
        foreach (ManagementObject printer in queryCollection)  
        {  
            if (string.Compare(printer["Name"].ToString(), PrinterName, true) == 0)  
            {  
                mo.InvokeMethod("SetDefaultPrinter", null);  
                reint = 1;  
                break;  
            }  
        }
public static String GetDefaultPrinters()
 {
            string searchQuery = "SELECT * FROM Win32_Printer",DefaultPrinterName;
       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();                                       
                }                         
            }
                return DefaultPrinterName;            
        }
上一篇下一篇

猜你喜欢

热点阅读