串口“打开/关闭”按钮不起作用

时间:2018-08-01 12:20:21

标签: c# winforms serial-port port

我试图用一个按钮打开和关闭我的COM端口。我可以打开并关闭它,但是在我想再次打开它之后,它捕获了第一个异常。

这是我的代码:

db.users.find( { "local": { email: "abc@hotmail.com" } } ).pretty()

首先,我的按钮说private void Button_Port_Open_Click(object sender, EventArgs e) { string Port_Name = ComboBox_Available_SerialPorts.SelectedItem.ToString(); int Baud_Rate = Convert.ToInt32(ComboBox_Standard_Baudrates.SelectedItem); COMport = new SerialPort(Port_Name, Baud_Rate, Parity.None, 8, StopBits.One); if (Button_Port_Open.Text == "Connect") { try { COMport.Open(); if (COMport.IsOpen == true) { Button_Port_Open.Text = "Disconnect"; #region EnableBoxes GroupBox_Port_Commands.Enabled = true; groupBox3.Enabled = true; groupBox4.Enabled = true; Button_Load_File.Enabled = false; #endregion TextBox_System_Log.Text = "***CONNECTED***" + Environment.NewLine + Port_Name + Environment.NewLine + Baud_Rate + " bps" + Environment.NewLine; COMport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); } else MessageBox.Show("Port could not be opened!"); } #region Port exceptions catch (UnauthorizedAccessException SerialException) { MessageBox.Show(SerialException.ToString()); COMport.Close(); } catch (System.IO.IOException SerialException) { MessageBox.Show(SerialException.ToString()); COMport.Close(); } catch (InvalidOperationException SerialException) { MessageBox.Show(SerialException.ToString()); COMport.Close(); } catch { MessageBox.Show("ERROR in Opening Serial Port -- UnKnown ERROR"); COMport.Close(); } #endregion } else { try { COMport.Close(); Button_Port_Open.Text = "Connect"; TextBox_System_Log.Text += "***DISCONNECTED***"; Thread.Sleep(5000); //Button_Port_Close.Enabled = false; } catch (Exception error) { MessageBox.Show(error.ToString()); } } } ,然后按它变成Connect(因此,if语句确定程序是否需要打开或关闭端口)。

0 个答案:

没有答案