首页 > 代码库 > .Net中获取打印机的相关信息

.Net中获取打印机的相关信息

新项目中牵涉到对打印机的一些操作,最重要的莫过于获取打印机的状态,IP等信息,代码量不大,但是也是自己花了一点时间总结出来的,希望能帮助需要的朋友。

代码如下:

using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace PrintCellLite.Model.Print
{
    class PrinterPropertyManager
    {
        /// <summary>
        /// 获取打印机的Location
        /// </summary>
        /// <param name="printerName">打印机名称</param>
        /// <returns>返回一个字符串</returns>
        public KeyValuePair<string,int> GetPrinterIPAndPort(string printerName)
        {
            string port = GetPortValue(printerName);
            if (string.IsNullOrEmpty(port)) { return new KeyValuePair<string, int>(); }
            //Query portName‘s property from regedit
            string[] portQuerys = GetPortQuerys(port);
            foreach (var portQuery in portQuerys)
            {
                RegistryKey portKey = Registry.LocalMachine.OpenSubKey(portQuery, RegistryKeyPermissionCheck.Default, System.Security.AccessControl.RegistryRights.QueryValues);
                if (portKey != null)
                {
                    object IPValue = http://www.mamicode.com/portKey.GetValue("IPAddress", String.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
                    object portValue = http://www.mamicode.com/portKey.GetValue("PortNumber", String.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
                    if (IPValue != null && portValue != null)
                    {
                        return new KeyValuePair<string, int>(IPValue.ToString(), (Int32)portValue);
                    }
                }
            }
            return new KeyValuePair<string,int>();
        }

        private string[] GetPortQuerys(string portName)
        {
            return new string[]
            {
                @"System\CurrentControlSet\Control\Print\Monitors\Advanced Port Monitor\Ports\" + portName,
                @"System\CurrentControlSet\Control\Print\Monitors\Local Port\Ports\" + portName,
                @"System\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\" + portName,
                @"System\CurrentControlSet\Control\Print\Monitors\USB Monitor\Ports\" + portName,
                @"System\CurrentControlSet\Control\Print\Monitors\WSD Port\Ports\" + portName,
            };
        }

        private string GetPortValue(string printerName)
        {

            string port = string.Empty;
            //Query printer‘s portName from WIN32_Printer
            string query = string.Format("SELECT * from Win32_Printer WHERE Name = ‘{0}‘", printerName);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection coll = searcher.Get();
            foreach (ManagementObject printer in coll)
            {
                PropertyData portNameProperty = printer.Properties["PortName"];
                if(portNameProperty != null)
                {
                    port = portNameProperty.Value.ToString();
                }
            }
            return port;
        }

        /// <summary>
        /// 获取打印机名字的列表
        /// </summary>
        /// <returns>返回一个ArrayList</returns>
        public ArrayList getPrinterName1()
        {
            ArrayList result = new ArrayList();

            foreach (string ss in PrinterSettings.InstalledPrinters)
            {
                result.Add(ss);
            }
            return result;
        }

        /// <summary>
        ///返回一个整形值,所代表的意思是打印机状态
        /// </summary>
        /// <param name="printerName">打印机名称</param>
        /// <returns>返回一个int值</returns>
        public int PrinterStatusInt(string printerName)
        {
            int ret = -1;
            string path = @"win32_printer.DeviceId=‘" + printerName + "‘";
            ManagementObject printer = new ManagementObject(path);
            printer.Get();
            ret = Convert.ToInt32(printer.Properties["PrinterStatus"].Value);
            return ret;
        }

        /// <summary>
        /// 获取打印机状态
        /// </summary>
        /// <param name="printerName">打印机名称</param>
        /// <returns>返回一个字符串</returns>
        public string GetPrinterStatus(string printerName)
        {
            int result = PrinterStatusInt(printerName);
            string status = "";
            switch (result)
            {
                case 1:
                case 2:
                    status = "Unknow";
                    break;
                case 3: status = "Ready";
                    break;
                case 4:
                case 7:
                    status = "Printing";
                    break;
                case 5: status = "Warning";
                    break;
                case 6: status = "Pause";
                    break;
                case 8: status = "Offline";
                    break;
                default: status = "Error";
                    break;
            }
            return status;
        }

        enum PrinterStatus
        {
            Other = 1,
            Unknow = 2,
            Ready = 3,
            Printing = 4,
            Warming = 5,
            Pause = 6,
            Printing1 = 7,
            Offline = 8
        }
    }


}