C#設定預設印表機-COM和WMI二種方式
阿新 • • 發佈:2019-02-17
COM方式:使用Winspool.drv
WMI方式:Class=Win32_ Printer 另注(Powershell中可以 gwmi -Class "Win32_Printer"找到List )
C#實現
Powershell 實現using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Runtime.InteropServices; namespace MyConsoleApp.Code { /// <summary> /// 設定或者獲取預設印表機類 /// </summary> public class PrintHelper { #region DllImport [DllImport("Winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool SetDefaultPrinter(string printerName); [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetDefaultPrinter(StringBuilder pszBuffer, ref int pcchBuffer); public static string GetDefaultPrinter() { const int ERROR_FILE_NOT_FOUND = 2; const int ERROR_INSUFFICIENT_BUFFER = 122; int pcchBuffer = 0; if (GetDefaultPrinter(null, ref pcchBuffer)) { return null; } int lastWin32Error = Marshal.GetLastWin32Error(); if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER) { StringBuilder pszBuffer = new StringBuilder(pcchBuffer); if (GetDefaultPrinter(pszBuffer, ref pcchBuffer)) { return pszBuffer.ToString(); } lastWin32Error = Marshal.GetLastWin32Error(); } if (lastWin32Error == ERROR_FILE_NOT_FOUND) { return null; } throw new Exception(Marshal.GetLastWin32Error().ToString()); } #endregion #region WMI方式 private static ManagementObjectSearcher query; private static ManagementObjectCollection queryCollection; private static ManagementObjectCollection GetManagementObjectCollection(string mql) { query = new ManagementObjectSearcher(mql); return query.Get(); } public static string GetDefaultPrinterByWMI() { queryCollection = GetManagementObjectCollection("SELECT * FROM Win32_Printer WHERE Default=true"); if (queryCollection != null) { foreach (ManagementObject mo in queryCollection) { return mo["Name"].ToString(); } return string.Empty; } else return string.Empty; } public static void SetDefaultPrinterByWMI(string PrinterName) { queryCollection = GetManagementObjectCollection("SELECT * FROM Win32_Printer"); if (queryCollection != null && queryCollection.Count > 0) { foreach (ManagementObject mo in queryCollection) { if (string.Compare(mo["Name"].ToString(), PrinterName, true) == 0) { mo.InvokeMethod("SetDefaultPrinter", null); break; } } } } #endregion } /* string printName = MyConsoleApp.Code.PrintHelper.GetDefaultPrinterByWMI(); MyConsoleApp.Code.PrintHelper.SetDefaultPrinterByWMI("Microsoft XPS Document Writer"); printName = MyConsoleApp.Code.PrintHelper.GetDefaultPrinterByWMI(); */ }
#當前預設印表機
Get-WmiObject -Query "select * from win32_printer where Default=true" ;
#另一種寫法,從印表機列表中查詢預設
$print=Get-WmiObject -Query "select * from win32_printer" ;
$print|%{if ($_.Default){$_.Name} }
#設定預設的方法
$print[0].SetDefaultPrinter()