1

Hi first of all i have looked already but didnt seem to get help with this issue.

Basically my application fires an event on data received from a serial port using this:

sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);

And i handle the data received using:

private static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        string inData;
        bool passed;
        SerialPort spRead = (SerialPort)sender;
        inData = spRead.ReadLine();
        TwinCat comm = new TwinCat();
        passed = comm.passiButton(inData);
        if (passed) comm.disposeComm();
        else MessageBox.Show("Error Closing Comm");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

In additional to that i have a checkbox control and i would like to pass if checked or not i.e. an extra bool variable so that i can change what to do with the data depending if the checkbox is checked or not.

Note that the conditions are not implemented yet as i cannot pass the bool variable in the event.

ThatBlairGuy
  • 2,426
  • 1
  • 19
  • 33
Combinu
  • 882
  • 2
  • 10
  • 31
  • I know i have already seen that post but i cannot figure out how to implement with that information. Can anyone please help me out on my code. – Combinu Feb 07 '14 at 12:03

1 Answers1

2

Assuming the CheckBox and SerialPort are in the same form...

Remove the static keyword from the event handler and then access non-GUI variables safely from the DataReceived event handler.

// member variable
// update the value during the checkbox's CheckChanged event handler
private bool isChecked;

private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    ...

    if (isChecked) 
    {
        // do something special
    }

    ...
}

EDIT: made changes to avoid cross-thread GUI operations

jglouie
  • 12,523
  • 6
  • 48
  • 65
  • Now i get a runtime error saying that: Control.Invoke must be used to interact with controls created in a seperate thread. – Combinu Feb 07 '14 at 12:11
  • Is reading the `Checked` property the only GUI/control operation you need to do? If it is, I would add a new member variable called `isChecked`, add a `CheckBox.CheckChanged` Event handler, and set the `isChecked` value in that handler. Then, in this snippet, check: `if (isChecked) { ... }` – jglouie Feb 07 '14 at 12:16
  • Ok ok i get it i made it and it works fine. THANKS!! – Combinu Feb 07 '14 at 12:21