如何连续检查串口状态

时间:2018-09-09 23:08:26

标签: c# serial-port

到目前为止,当我运行我的应用程序时,我可以检测到连接到PC的任何端口,但可以说,我正在运行该程序时断开了该端口的连接并重新连接,因此如何在程序运行时检测该端口运行?就像Tera Term或Docklight。 我的猜测之一是运行计时器,但我想知道是否有人可以帮助我。因为我对port的功能不是很熟悉。

    // Fonction Configuration Port Terminal
    void ConfigurationTerminal()
    {
        if (Serial_Port_1.IsOpen == false)
        {

            // Port Configuration
            Serial_Port_1.PortName = (string)cbn_Port.SelectedItem;
            Serial_Port_1.BaudRate = Baudrate;
            // Parity Configuration 
            switch (OptionalParity)
            {
                case 0: Serial_Port_1.Parity = Parity.None; break;
                case 1: Serial_Port_1.Parity = Parity.Even; break;
                case 2: Serial_Port_1.Parity = Parity.Odd; break;
                default: Serial_Port_1.Parity = Parity.None; break;
            }

            Serial_Port_1.DataBits = DataBits;
            switch (OptionalStopBit)
            {
                case 0: Serial_Port_1.StopBits = StopBits.One; break;
                case 1: Serial_Port_1.StopBits = StopBits.OnePointFive; 
                break;
                case 2: Serial_Port_1.StopBits = StopBits.Two; break;
                default: Serial_Port_1.StopBits = StopBits.One; break;
            }
            Serial_Port_1.StopBits = StopBits.One;
            Serial_Port_1.Handshake = Handshake.None;

            // Set the read/write timeouts
            Serial_Port_1.ReadTimeout = 500;
            Serial_Port_1.WriteTimeout = 500;
            try
            {
                Serial_Port_1.Open();
                BackColor = Color.Green;
                Txt_DataSend.Text = "I'm ready to receive the data.\r\n";
                FlagRdyToSend = "1";
                Serial_Port_1.Write(FlagRdyToSend);
            }
            catch (Exception ex)
            {
                BackColor = Color.Red;
                MessageBox.Show(ex.Message, "Message");
            }
        }
        else
        {
            BackColor = Color.Green;
        }
    }

0 个答案:

没有答案