C # trackbad not updating

I ran into this rather complex issue lately and I was hoping someone could help me.

I have a program that uses trackballs to display audio volume and is controlled by an Arduino via a serial port.

When I try to change the value (programmaticaly) of the trackar (move the slider) in any way, it works fine with the following code:

trackbar1.Value = ...;

      

However, when I put this in my serial data handler, it doesn't work: /

I declare a serial data handler like this:

//declaring arduinoCom
public SerialPort arduinoCOM;

//In form1
arduinoCOM.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

      

my handler looks like this:

public void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        trackBar2.Value = 50;

    }

      

Serial communication works flawlessly and the handler doesn't work seamlessly.

I have tried for 2 days now and I was able to determine that the only difference between a working trackbar and a non-working trackbar is where the "trackbar1.value" is. So I can remove the remaining (hopefully) unrecognizable code for clarity.

So my question is, why doesn't the Trackbar slider move when I try to change its value outside of the "standards method"

Additional info: I tried to run the program and then paused it with visual stuio and trackbar.Value was changed successfully, the only thing that doesn't work is the graphical side.

I have tested several trackbars and tried to use

trackbar1.Refresh();

      

he did not work

Display of trackbar values โ€‹โ€‹1 and 2, and display of all 5: Trackball values

trackballs don't move

+3


source to share


2 answers


The DataReceived event for the SerialPort is thrown on a second thread (not on the UI thread) from which you cannot modify interface elements. Using "Invoke" you can make changes to the UI thread Instead

public void DataReceivedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)
{
    trackBar2.Value = 50;

}

      



using:

public void DataReceivedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)
{
    if (trackbBar2.IsHandlecreated) trackBar2.Invoke(new Action(() =>  trackbar.Value = 50));
}

      

+5


source


I found the problem when I was declaring my serial communication I used `

   Form1 form1 = new Mixer.Form1();
   initialiseSerialEventHandler(arduinoCOM);

      



and instead I have to use

       initialiseSerialEventHandler(arduinoCOM);

      

+1


source







All Articles