I am trying to update a label from a BackgroundWorker thread that calls a method from another class outside the Form. So I basically want to do this:
MainForm.counterLabel.Text = Counter.ToString();
but the label is private. I have looked into things like using BackgroundWorker's progressupdate function, invoke, etc but they don't seem to be what I need.
here is some more of my code:
the MainForm:
clickThread.DoWork += (s, o) => { theClicker.Execute(speed); };
clickThread.RunWorkerAsync();
The Class/Method called:
public void Execute(int speed)
{
while (running)
{
Thread.Sleep(speed);
Mouse.DoMouseClick();
Counter++;
//Update UI here
}
}
I think I have overly complicated my code a bit :\ and backed myself into a corner.
Tomtom :
You should use the ProgressChanged-Event to update the UI. The code for the BackgroundWorker should look something like:\n\ninternal static void RunWorker()\n{\n int speed = 100;\n BackgroundWorker clickThread = new BackgroundWorker\n {\n WorkerReportsProgress = true\n };\n clickThread.DoWork += ClickThreadOnDoWork;\n clickThread.ProgressChanged += ClickThreadOnProgressChanged;\n clickThread.RunWorkerAsync(speed);\n\n}\n\nprivate static void ClickThreadOnProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n\n someLabel.Text = (string) e.UserState;\n\n}\n\nprivate static void ClickThreadOnDoWork(object sender, DoWorkEventArgs e)\n{\n BackgroundWorker worker = (BackgroundWorker)sender;\n int speed = (int) e.Argument;\n\n while (!worker.CancellationPending)\n {\n Thread.Sleep(speed);\n Mouse.DoMouseClick();\n Counter++;\n worker.ReportProgress(0, \"newText-Parameter\");\n }\n}\n\n\n}",
2016-04-13T07:33:15