0

我有一个程序需要从软件启动到关闭的那一刻打开串行端口连接。

我的程序在计算机启动时启动(它在%startup%文件夹中有一个快捷方式 - Windows 7)。

我正在使用进程资源管理器(由 Sysinternals监控我的串行端口)。当一切正常时,我确实在那里看到了我的开放端口。但有时在计算机打开后(正常应用程序关闭后)我收到错误访问端口“com1”被拒绝,我在进程资源管理器中看到的只是SMSvcHost.exe

这是开放的串行连接方法

static class CVFeedSerialUtilsV2
{
    static string com = GetSerialPortComName();           
    const int sleepTimeInMs = 50;   

   private static SerialPort port = new SerialPort(com, 9600, Parity.None, 8, StopBits.One);

        public static SerialPort Port
        {
            get { return port; }

        }           

        public static void readAndOpenSerialPort()
        {    
            try
            {   
               if (String.IsNullOrEmpty(com))
                {
                    return;
                }  


                if (port != null && port.IsOpen)
                    port.Close();    

                if (!port.IsOpen)
                {

                    port.DtrEnable = true;    // Data-terminal-ready
                    port.RtsEnable = true;    // Request-to-send

                    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
                    port.Open();                       
                }                   

            }

        }

        public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //do stuff
        }
   }

这是我的表单关闭方法

private void frmBase_FormClosing(object sender, FormClosingEventArgs e)
    {
        try
        {

            //wait for some amount of time after calling the Close method before attempting to call the Open method, 
            //as the port may not be closed instantly.
            if (CVFeedSerialUtilsV2.Port != null && CVFeedSerialUtilsV2.Port.IsOpen)
            {
                CVFeedSerialUtilsV2.Port.DiscardInBuffer();
                CVFeedSerialUtilsV2.Port.DiscardOutBuffer();
                CVFeedSerialUtilsV2.Port.DataReceived -= CVFeedSerialUtilsV2.port_DataReceived;
                CVFeedSerialUtilsV2.Port.Close();
               //CVFeedSerialUtilsV2.Port.Dispose();
            }
            System.Threading.Thread.Sleep(1000);

        }
        catch (Exception ex)
        {


        }
    }

这就是我获取串口的方式

private static string GetSerialPortComName()
        {
            try
            {
                List<string> list = new List<string>();
                string name = "";
                ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity");
                foreach (ManagementObject mo2 in searcher2.Get())
                {
                    if (mo2["Name"] != null)
                    {
                        name = mo2["Name"].ToString();
                        // Name will have a substring like "(COM12)" in it.
                        if (name.Contains("(COM"))
                        {
                            list.Add(name);
                        }
                    }
                }
                // remove duplicates, sort alphabetically and convert to array
                string[] usbDevices = list.Distinct().OrderBy(s => s).ToArray();
                foreach (String s in usbDevices)
                {

                    if (s.ToLower().Contains("port"))
                    {
                        int start = s.IndexOf("(COM") + 1;
                        if (start >= 0)
                        {
                            int end = s.IndexOf(")", start + 3);
                            if (end >= 0)
                            {
                                // cname is like "COM14"
                                return s.Substring(start, end - start);

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {


            }

            return "";
        }
4

0 回答 0