Wednesday, October 13, 2010

C# Tutorial: Cross-Threading [Access a Form from a different Thread]

Here is the code

using System.Threading;
///////////////////////////////////////////
public Form1()
{
    InitializeComponent();
    // Create a new thread for Form2.
    Thread frm2 = new Thread(new ThreadStart(startForm2));
    frm2.Start(); 
}
Form2 form2 = new Form2(); 
public void startForm2()
{
    Application.Run(form2);   
}

public void transferText(string text)
{
    // Invoke the method of Form2's textBox1
    if (form2.textBox1.InvokeRequired)
        form2.textBox1.Invoke((MethodInvoker)delegate()
        {
            transferText(text);
        });
    else form2.textBox1.Text = text;
}

public void close()
{
    if (form2.textBox1.InvokeRequired)
        form2.textBox1.Invoke((MethodInvoker)delegate()
        {
            close();
        });
    else form2.Close();
}

private void button1_Click(object sender, EventArgs e)
{
    transferText(textBox1.Text);  
}

private void button2_Click(object sender, EventArgs e)
{
    close();
}

Or download the solution

No comments:

Post a Comment