C# 获取打印机端口列表

本文介绍了三种C#获取打印机端口信息的方法:1) 使用Win32_TCPIPPrinterPort获取TCP/IP端口;2) 通过注册表获取COM、LPT和本地端口;3) 利用WinAPI枚举所有打印机端口,包括LPT、COM和USB等。这些方法可以帮助开发者全面了解系统的打印机端口配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,使用Win32_TCPIPPrinterPort来获取打印机的 TCP IP端口

        /// <summary>
        /// 获取本地打印机TCPIP名字192.168.0.1 Win32_TCPIPPrinterPort
        /// </summary>
        /// <returns></returns>
        private List<string> GetLocalPrinterTcpIpList()
        {
            List<string> listCom = new List<string>();
            ManagementScope scope = new ManagementScope(@"\root\cimv2");
            //获取打印机IP名字  192.168.0.1 Win32_TCPIPPrinterPort
            var vComs = new ManagementObjectSearcher(scope, new ObjectQuery("select * from Win32_TCPIPPrinterPort")).Get();
            foreach (var vCom in vComs)
            {
                listCom.Add(vCom.Properties["Name"].Value.ToString());
            }
            return listCom;
        }

2,使用注册表方式来获取打印机的COM口,LPT端口,以及本地端口

        /// <summary>
        /// 获取打印机COM LPT Local三种端口 
        /// </summary>
        /// <returns></returns>
        private List<string> GetPrinterComLptLocalPort()
        {
            List<string> listRet = new List<string>();
            string strLocalPortPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Ports";
            RegistryKey localMachineReg = Registry.LocalMachine;
            RegistryKey reg = null;
            reg = localMachineReg.OpenSubKey(strLocalPortPath, true); //用于读写

            foreach (var vItem in reg.GetValueNames())
            {
                if (vItem.Contains("Ne") && vItem.LastIndexOf(':') == vItem.Length - 1)  //Ne开头的并且是冒号结尾的不加入端口中
                {
                    continue;
                }
                listRet.Add(vItem);
            }
            localMachineReg.Close();

            return listRet;
        }

3,使用Win API获取(上述两种方式获取不是很全面),使用Win API 可以获取到LPT,COM ,USB等和在windows控制面板中 打印机端口列表看到的是一样的

    class Myclass
    {
        //PortType enum
        //struct for PORT_INFO_2
        [StructLayout(LayoutKind.Sequential)]
        public struct PORT_INFO_2
        {
            public string pPortName;
            public string pMonitorName;
            public string pDescription;
            public PortType fPortType;
            internal int Reserved;
        }


        [Flags]
        public enum PortType : int
        {
            write = 0x1,
            read = 0x2,
            redirected = 0x4,
            net_attached = 0x8
        }

        //Win32 API
        [DllImport("winspool.drv", EntryPoint = "EnumPortsA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern int EnumPorts(string pName, int Level, IntPtr lpbPorts, int cbBuf, ref int pcbNeeded, ref int pcReturned);


        /// <summary>
        /// method for retrieving all available printer ports
        /// </summary>
        /// <returns>generic list populated with post names (i.e; COM1, LTP1, etc)</returns>

        public List<string> GetPortNames()
        {
            //variables needed for Win32 API calls
            int result; int needed = 0; int cnt = 0; IntPtr buffer = IntPtr.Zero; IntPtr port = IntPtr.Zero;

            //list to hold the returned port names
            List<string> ports = new List<string>();

            //new PORT_INFO_2 for holding the ports
            PORT_INFO_2[] portInfo = null;

            //enumerate through to get the size of the memory we need
            result = EnumPorts("", 2, buffer, 0, ref needed, ref cnt);
            try
            {
                //allocate memory
                buffer = Marshal.AllocHGlobal(Convert.ToInt32(needed + 1));

                //get list of port names
                result = EnumPorts("", 2, buffer, needed, ref needed, ref cnt);

                //check results, if 0 (zero) then we got an error
                if (result != 0)
                {
                    //set port value
                    port = buffer;

                    //instantiate struct
                    portInfo = new PORT_INFO_2[cnt];

                    //now loop through the returned count populating our array of PORT_INFO_2 objects
                    for (int i = 0; i < cnt; i++)
                    {
                        portInfo[i] = (PORT_INFO_2)Marshal.PtrToStructure(port, typeof(PORT_INFO_2));
                        port = (IntPtr)(port.ToInt64() + Marshal.SizeOf(typeof(PORT_INFO_2)));
                    }
                    port = IntPtr.Zero;
                }
                else
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                //now get what we want. Loop through al the
                //items in the PORT_INFO_2 Array and populate our generic list
                for (int i = 0; i < cnt; i++)
                {
                    ports.Add(portInfo[i].pPortName);
                }

                //sort the list
                ports.Sort();

                return ports;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error getting available ports: {0}", ex.Message));
                Console.ReadLine();
                return null;
            }
            finally
            {
                if (buffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buffer);
                    buffer = IntPtr.Zero;
                    port = IntPtr.Zero;
                }
            }

        }


    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值