private void button3_Click(object sender, EventArgs e)
{
SerialPort sp = new SerialPort();
if (button3.Text == "连接串口")
{
if (comboBox1.SelectedIndex != -1 &&
comboBox2.SelectedIndex != -1 &&
comboBox3.SelectedIndex != -1 &&
comboBox4.SelectedIndex != -1 &&
comboBox5.SelectedIndex != -1)
{
try
{
sp.PortName = comboBox1.SelectedItem.ToString();
sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem);
sp.DataBits = Convert.ToInt32(comboBox5.SelectedItem);
#region
switch (comboBox3.SelectedItem.ToString())
{
case "None":
sp.Parity = Parity.None;
break;
case "奇校验":
sp.Parity = Parity.Odd;
break;
case "偶校验":
sp.Parity = Parity.Even;
break;
}
switch (comboBox4.SelectedItem.ToString())
{
case "0":
sp.StopBits = StopBits.None;
break;
case "1":
sp.StopBits = StopBits.One;
break;
case "1.5":
sp.StopBits = StopBits.OnePointFive;
break;
case "2":
sp.StopBits = StopBits.Two;
break;
}
sp.Open();
button3.Text = "关闭串口";
MessageBox.Show("连接成功");
#endregion
}
catch (Exception ex)
{
MessageBox.Show("打开串口失败:" + ex.ToString());
}
}
else
{
MessageBox.Show("连接失败,请选择正确的端口");
}
}
else
{
sp.Close();
button3.Text = "连接串口";
}
当你点击关闭串口时,你这个点击事件先实例化了一个SerialPort类的对象,然后把它关闭了,然后把button文本变成了连接串口,就这样,而你之前最开始点击连接串口创建的SerialPort对象还在占用着COM口,你并没有把它关闭,所以当你再次点击时会提示被占用
你不应该在这个方法里实例化SerialPort类