亲宝软件园·资讯

展开

C#获取打印机列表

edielei 人气:0

方法一

第一步:添加引用

using System.Printing;

第二步:代码

public static List<string> GetPrintList()
{
    List<string> lt = new List<string>();
    LocalPrintServer printServer = new LocalPrintServer();
    PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local });
    foreach (PrintQueue printer in printQueuesOnLocalServer)
        lt.Add(printer.Name);
    return lt;
}

方法二

需要引入

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;
        }
    }

到此这篇关于C#获取打印机列表的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论