重启计算机后,串行端口有时仍保持打开状态

时间:2018-08-20 13:57:45

标签: c# .net winforms serial-port system.management

我有一个程序,要求从软件启动到关机为止都打开串行端口连接。

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

我正在使用进程浏览器(by 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 "";
        }

0 个答案:

没有答案