Reputation: 83
i've run into this pretty tricky problem recently and i hoped somebody could help me.
i have a program that uses trackbars as to display sound volume and it's controlled with an Arduino via serial.
When i try to modify the value (programmaticaly) of the trackar (moving the slider) in any method, it works perfectly with the following code :
trackbar1.Value = ...;
However, when i put this in my serial data handler, it doesn't works :/
I declare the serial data handler this way :
//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;
}
The serial communication works flawlessly, and the handler does it's job no problem.
I've tried for 2 days now and i was able to identify that the only difference between the working trackbar and the not-working one is where the "trackbar1.value" is located. So i've remove the rest of the (i hope) unessecary code for clarity reasons.
So my Question is why does the Trackbar slider doesn't move when i try to modify it's value outside of the "standards method"
additional informations : I've tried runnning the program and then pausing it with visual stuio and the trackbar.Value has been changed successfully, the only thing that isn't working is the graphics side.
I've tested with multiple trackbars, and tried using
trackbar1.Refresh();
it didn't work
Picture of the value of trackbar 1 and 2 as well as picture of all 5 : Values of trackbars
Upvotes: 3
Views: 1307
Reputation: 83
I found the problem, when i was declaring my serial communication i was using `
Form1 form1 = new Mixer.Form1();
initialiseSerialEventHandler(arduinoCOM);
and instead i should only use
initialiseSerialEventHandler(arduinoCOM);
Upvotes: 1
Reputation: 3285
The DataReceived event for SerialPort is raised on a secundary thread (not the UI thread) from which you cannot change UI elements. Using 'Invoke', you can make the change in the UI thread Instead of
public void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
trackBar2.Value = 50;
}
use:
public void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
if (trackbBar2.IsHandlecreated) trackBar2.Invoke(new Action(() => trackbar.Value = 50));
}
Upvotes: 4