I cannot figure out how to make a C# Windows Form application write to a textbox from a thread. For example in the Program.cs we have the standard main() that draws the form:
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); }
Then we have in the Form1.cs:
public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public static void SampleFunction() { while(true) WindowsFormsApplication1.Form1.ActiveForm.Text += 'hi. '; }
Am I going about this completely wrong?
UPDATE
Here is the working code sample provided from bendewey:
public partial class Form1 : Form { public Form1() { InitializeComponent(); new Thread(SampleFunction).Start(); } public void AppendTextBox(string value) { if (InvokeRequired) { this.Invoke(new Action<string>(AppendTextBox), new object[] {value}); return; } textBox1.Text += value; } void SampleFunction() { // Gets executed on a seperate thread and // doesn't block the UI while sleeping for(int i = 0; i<5; i++) { AppendTextBox('hi. '); Thread.Sleep(1000); } } }
On your MainForm make a function to set the textbox the checks the InvokeRequired
although in your static method you can’t just call.
you have to have a static reference to the Form1 somewhere, but this isn’t really recommended or necessary, can you just make your SampleFunction not static if so then you can just call
It will append on a differnt thread and get marshalled to the UI using the Invoke call if required.
Full Sample