c#串口关闭

时间:2017-06-07 12:56:12

标签: c#

已在Form1Form2

中使用此课程
public class DataInput
{
    public event Action<string> DataReceived;

    private readonly SerialPort mySerialPort;

    public DataInput(string portName)
    {
        mySerialPort = new SerialPort();
        mySerialPort.PortName = portName;
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
        mySerialPort.Open();
    }

    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string received = mySerialPort.ReadExisting();
        DataReceived?.Invoke(received);
    }
}

现在当我用Form2关闭this.Close();时,我也需要关闭Serial port。 因为当我再次打开表单时,它会显示Access to the port 'COM1' is denied.

我如何关闭端口??

2 个答案:

答案 0 :(得分:2)

您需要关闭串口连接。您可以在Form2结束事件中调用mySerialPort.Close(),如下所示:

private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(mySerialPort.IsOpen)
  {
    mySerialPort.Close();
  }
}

答案 1 :(得分:2)

结合@Ketan的解决方案和您的代码:

public class DataInput
{
    public event Action<string> DataReceived;

    ...

    public void Close()
    {
        if(mySerialPort.IsOpen)
        {
            mySerialPort.Close();
        }
    }
}

在Form2中:

private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    dataInput.Close();
}