当前位置:编程学习 > C#/ASP.NET >>

c# CS结构 如何取得COM口装备

问题描述:现在需要在窗口打开时能获取到当前机器的COM口信息。比如打开状态等等 --------------------编程问答-------------------- 这个情况你最好先用串口调试助手来看了再选择串口几是好的 --------------------编程问答-------------------- 利用以下的方面返回本地串口信息,再进行循打开,如打开失败的记录下来,最终返回.
打开失败:只是可以断定他目前不可连接.

#region 调用注册表返回本地串口
        /// <summary>
        /// 串口函数(方法需调用注册表,串口编程所用类)
        /// </summary>
        /// 使用命名空间:
        /// using System.Security;
        /// using System.Security.Permissions;
        /// <returns>返回此计算机串口数组</returns>
        public static string[] GetPortNames()//
        {
            RegistryKey localMachine = null;
            RegistryKey key2 = null;
            string[] textArray = null;//这里有个判断,判断该注册表项是否存在    
            new RegistryPermission(RegistryPermissionAccess.Read, @"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM").Assert();
            try
            {
                localMachine = Registry.LocalMachine;
                key2 = localMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM", false);
                if (key2 != null)
                {
                    string[] valueNames = key2.GetValueNames();
                    textArray = new string[valueNames.Length];
                    for (int i = 0; i < valueNames.Length; i++)
                    {
                        textArray[i] = (string)key2.GetValue(valueNames[i]);
                    }
                }
            }
            finally
            {
                if (localMachine != null)
                {
                    localMachine.Close();
                } if (key2 != null)
                {
                    key2.Close();
                }
                CodeAccessPermission.RevertAssert();
            } if (textArray == null)
            {
                textArray = new string[0];
            }
            return textArray;
        }
        #endregion
--------------------编程问答--------------------  private System.IO.Ports.SerialPort serialPort1;//使用c#的SerialPort类

//设置serialPort1的串口属性
serialPort1.PortName = cmbPortName.Text;//比如cmbPortName.Text="com1"
serialPort1.BaudRate = int.Parse(cmbBaudRate.Text);//设置波特率
serialPort1.DataBits = int.Parse(cmbDataBits.Text);//设置数据位
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);//停止位
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);//校验位

//打开串口
serialPort1.Open();

//关闭串口
 serialPort1.Close();



--------------------编程问答-------------------- C#中关于串口的监听,你参考一下吧!


using System; 
using System.IO.Ports; 
using System.Threading; 
using System.Text; 

namespace Tangxu.Common 

    public class ReadCom 
    { 
        public ReadCom() 
        { 
            _ReadConfig = new ReadConfigure(System.Environment.CurrentDirectory + "\\Com_Info.xml"); 
        } 

        public ReadCom(string sCom,int nBaud):this() 
        { 
        
        } 

        private byte[] _ReadBuffer; 
        private SerialPort ss_port = new SerialPort(); 
        private static int nReadCount = 0; 
        private ReadConfigure _ReadConfig; 

        #region Initialize com port 

        public bool InitCom()//初始化建串口类实例 
        { 
          // return true; 
            try 
            { 
                ss_port.PortName = _ReadConfig.GetNodeValue("PORT");// _sComPort; 
                ss_port.BaudRate = int.Parse(_ReadConfig.GetNodeValue("BAUD"));//_nBaud; 
                ss_port.ReadBufferSize = 10240; 
                ss_port.DataBits = int.Parse(_ReadConfig.GetNodeValue("DATA"));//8; 
                switch (_ReadConfig.GetNodeValue("PARITY")) 
                { 
                    case "None": 
                        ss_port.Parity = Parity.None; 
                        break; 
                    case "Even": 
                        ss_port.Parity = Parity.Even; 
                        break; 
                    case "Mark": 
                        ss_port.Parity = Parity.Mark; 
                        break; 
                    case "Odd": 
                        ss_port.Parity = Parity.Odd; 
                        break; 
                    case "Space": 
                        ss_port.Parity = Parity.Mark; 
                        break; 
                } 
                switch (_ReadConfig.GetNodeValue("STOP")) 
                { 
                    case "1": 
                        ss_port.StopBits = StopBits.One; 
                        break; 
                    case "1.5": 
                        ss_port.StopBits = StopBits.OnePointFive; 
                        break; 
                    case "2": 
                        ss_port.StopBits = StopBits.Two; 
                        break; 
                } 
                ss_port.ReadTimeout = 600; 
                ss_port.WriteTimeout = 700; 

                ss_port.Open();//打开串口 
                return true; 
            } 
            catch (Exception ex) 
            { 
                throw new Exception("打开串口失败!\r\n错误信息:" + ex.Message); 
            } 
        } 
        #endregion 

        #region FreeDrv 
        /// <summary> 
        /// free opw 
        /// </summary> 
        public void FreeDrv() 
        { 
            try 
            { 
                if (ss_port != null) 
                {                  
                    ss_port.Close();  
                } 
            } 
            catch 
            { } 
        } 
        #endregion 

        #region Write command to OPW 
        /// <summary> 
        /// 发操作命令给OPW设备 
        /// 并返回状态 
        /// </summary> 
        /// <param name="sCommand"> </param> 
        /// <returns> </returns> 
        public string WriteCommand(string sCommand) 
        { 
            StringBuilder sb = new StringBuilder(); 
            bool bRead = true; 
            try 
            { 
                ss_port.DiscardInBuffer(); 
                ss_port.Write(sCommand); 
                Thread.Sleep(1500); 
                while (bRead) 
                { 
                    _ReadBuffer = new byte[ss_port.BytesToRead]; 
                    ss_port.Read(_ReadBuffer, 0, _ReadBuffer.Length); 
                    sb.Append(Encoding.ASCII.GetString(_ReadBuffer)); 
                    Thread.Sleep(500); 
                    if (ss_port.BytesToRead <= 0) 
                    { 
                        bRead= false; 
                    } 
                } 
                if (sb.ToString().Length== 0) 
                { 
                    nReadCount++; 
                } 

                if (nReadCount == 3) 
                { 
                    nReadCount = 0; 
                    throw new Exception("设置不正确或没有联接设备!"); 
                }              
            } 
            catch (Exception ex) 
            { 
                throw new Exception("从设备获取数据失败!\r\n错误信息:" + ex.Message); 
            } 
            return sb.ToString(); ; 
        } 

        public string WriteCommand(byte[] bCommand) 
        { 
            StringBuilder sb = new StringBuilder(); 
            bool bRead = true; 
            try 
            { 
                ss_port.DiscardInBuffer(); 
                ss_port.Write(bCommand,0,bCommand.Length); 
                Thread.Sleep(1500); 
                while (bRead) 
                { 
                    _ReadBuffer = new byte[ss_port.BytesToRead]; 
                    ss_port.Read(_ReadBuffer, 0, _ReadBuffer.Length); 
                    sb.Append(Encoding.ASCII.GetString(_ReadBuffer)); 
                    Thread.Sleep(500); 
                    if (ss_port.BytesToRead <= 0) 
                    { 
                        bRead = false; 
                    } 
                } 
                if (sb.ToString().Length == 0) 
                { 
                    nReadCount++; 
                } 

                if (nReadCount == 3) 
                { 
                    nReadCount = 0; 
                    throw new Exception("设置不正确或没有联接设备!"); 
                }              
            } 
            catch (Exception ex) 
            { 
                throw new Exception("从设备获取数据失败!\r\n错误信息:" + ex.Message); 
            } 
            return sb.ToString(); 
        } 
        #endregion 

        #region Get All COM Port 
        public string[] GetAllComPort() 
        { 
            string[] sAllPort = null; 
            try 
            { 
                sAllPort = SerialPort.GetPortNames(); 
            } 
            catch (Exception ex) 
            { 
                throw new Exception("获取计算机COM口列表失败!\r\n错误信息:" + ex.Message); 
            } 
            return sAllPort; 
        } 
        #endregion 
    } 



--------------------编程问答-------------------- mark
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,