COM方式:使用Winspool.drv
WMI方式:Class=Win32_ Printer 另注(Powershell中可以 gwmi -Class "Win32_Printer"找到List )
C#实现
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()
3938



被折叠的 条评论
为什么被折叠?



