关闭端口时出现问题

时间:2015-06-21 02:47:26

标签: c# serial-port ioexception

我正在将Arduino信息读入C#但是当我想通过按btnStop来停止阅读信息时,我总是得到" IOException未处理"为什么呢?

显示的错误在下面评论。 C#代码如下:

 public Form1()
    {
        InitializeComponent();
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = txtPortName.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.Open();

        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        serialPort1.DataReceived += serialPort1_DataReceived;
    }

    void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            Data = serialPort1.ReadLine(); //----->>>ERROR SHOWN HERE
            this.Invoke(new EventHandler(displaydata_event));
        }
        catch (IOException ex5)
        {
            MessageBox.Show("ERROR:" + ex5);
        }
    }

    void displaydata_event(object sender, EventArgs e)
    {
        txtData.AppendText(Data + "\n");
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        try
        {
            serialPort1.Close();
        }
        catch (IOException ex2)
        {
            txtData.AppendText("Close error: " + ex2 + "\n");
        }
    }
}

0 个答案:

没有答案