0

In my form I have a button that opens a connection to a serial port when clicked on. I have images and label text that change depending on the state of the process: loading, success, failure, disconnected (for when I click on the "Disconnect" button). This is my code:

private void btnConnect_Click(object sender, EventArgs e)
        {
            btnConnect.Enabled = false;
            picSuccess.Visible = picFail.Visible = picDisconnected.Visible = false;
            picLoading.Visible = true;
            lblConnection.Text = "Connecting...";

            try
            {
                SerialPortClass.GetInstance().Connect(cmbDevice.Text, Convert.ToInt32(cmbBaud.Text));
            }
            catch(Exception ex)
            {
                lblConnection.Text = "Connection failed! ";
                if (ex is ArgumentException)
                    lblConnection.Text += "Invalid port name.";
                else if (ex is UnauthorizedAccessException)
                    lblConnection.Text += "Unauthorized access.";
                else if (ex is InvalidOperationException)
                    lblConnection.Text += "Port already in use by another application.";
                else if (ex is System.IO.IOException)
                    lblConnection.Text += "Invalid port state.";

                picLoading.Visible = picSuccess.Visible = picDisconnected.Visible = false;
                picFail.Visible = true;
                return;
            }

            picLoading.Visible = picFail.Visible = picDisconnected.Visible = false;
            picSuccess.Visible = true;
            lblConnection.Text = "Connection successful!";
            btnDisconnect.Enabled = true;
        }

The problem is that the loading picture and "Connecting..." label text never show up. I added the Thread.Sleep() function before the "try" statement since I thought it was because the connection was being established too quickly, but that only made the form not display anything until it jumped to the Success state.

Debugging the button click event shows that changes to what picture is visible and what text is in the label only apply once the event is finished. Is this the normal functionality? Would there be a way to work around it?

Rod1022
  • 13
  • 5

0 Answers0