dimanche 21 août 2016

Frozen windows form application with checkbox c#

Here is my situation, when I check the checkbox, my application freezes but still works. Which means that it is still able to recognize data sent through the serial port; for testing purposes it just exits the application.

If I comment out line 45 ("pipe = arduino.ReadLine();" see screenshot below) meaning that it no longer has to "ReadLine()", I am able to un-check the box. However now when I try to re-check the box, I get an error message saying "Access to the port 'COM5' is denied"

I assume that the code cannot continue because it is trying to "ReadLine()" when nothing has been sent through yet. However I do not have an explanation for being denied access to the COM port; rather than me trying to open the port when its already opened.

private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {

        SerialPort arduino = new SerialPort();
        arduino.BaudRate = 9600;
        arduino.PortName = comboBox1.Text;
        string pipe;

        if (checkBox1.Checked)
        {
            checkBox1.Text = "Listening...";
            arduino.Open();
                pipe = arduino.ReadLine();
                if (pipe == "S\r")
                {
                    //System.Diagnostics.Process.Start("shutdown", "/f /r /t 0");
                    System.Windows.Forms.Application.Exit();
                }
        else
        {
            checkBox1.Text = "Start";
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire