引言
需要引入
System.Drawing.Printing
System.Management
实现
1.获取打印机列表
2.获取默认打印机
3.设置默认打印机
上代码
public class PrinterExample
{
/// <summary>
/// 设置默认打印机
/// </summary>
/// <param name="Name"></param>
/// <returns></returns>
[DllImport("winspool.drv")]
public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
/// <summary>
/// 获取默认打印机
/// </summary>
/// <returns></returns>
public static string GetDefaultPrinter()
{
PrintDocument print = new PrintDocument();
string defaultName = print.PrinterSettings.PrinterName;//默认打印机名
return defaultName;
}
/// <summary>
/// 获取本地所有打印机
/// </summary>
/// <returns></returns>
public static List<String> GetLocalPrinters()
{
List<String> printer_names = new List<String>();
foreach (String item in PrinterSettings.InstalledPrinters)
{
printer_names.Add(item);
}
return printer_names;
}
/// <summary>
/// 获取本地所有打印机 System.Management方式获取
/// </summary>
/// <returns></returns>
public static List<String> GetLocalPrinters2()
{
List<String> printer_names = new List<String>();
ManagementObjectCollection queryCollection;
string _classname = "SELECT * FROM Win32_Printer";
Dictionary<string, ManagementObject> dict = new Dictionary<string, ManagementObject>();
ManagementObjectSearcher query = new ManagementObjectSearcher(_classname);
queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
string oldName = mo["Name"].ToString();
printer_names.Add(oldName);
}
return printer_names;
}
}
网友评论