C#獲取打印機列表方法介紹

方法一

第一步:添加引用

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#獲取打印機列表的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: