1

I have a main that start a thread for my form. I want to update the label1 text from the main thread. I have created my delegate and my method to update it but i don't know how to access the form thread and to modify the label1 text.

Here my code for the main:

public class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>

    [STAThread]
    static void Main()
    {
        //Thread l'affichage de la form
        Program SecondThread = new Program();
        Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));
        th.Start();  

        //Update the label1 text

    }

    public void ThreadForm()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

    }

}

Here the code for my form1:

 public partial class Form1 : Form
{

    public delegate void SetTextLabelDelegate(string text);

    public void SetTexLabel(string text)
    {
        if (this.label1.InvokeRequired)
        {
            SetTextLabelDelegate SetLabel = new SetTextLabelDelegate(SetTexLabel);
            this.Invoke(SetLabel, new object[] { text });
        }
        else
        {
            this.label1.Text = text;
            this.Refresh();
        }       
    }

    public Form1()
    {
        InitializeComponent();
    }
}

How can i access to the form thread and to modify the label1 text ? I am using C# and .Net 4.5.

Damaelios
  • 23
  • 3

1 Answers1

1

You'll need to have access to the Form object on the second thread, so you'd need to expose it in your Program class. Then, in your main, you should be able to set it via that exposed property.

public class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>

    [STAThread]
    static void Main()
    {
        //Thread l'affichage de la form
        Program SecondThread = new Program();
        Thread th = new Thread(new ThreadStart(SecondThread.ThreadForm));
        th.Start();  

        //Update the label1 text
        while (SecondThread.TheForm == null) 
        {
          Thread.Sleep(1);
        } 
        SecondThread.TheForm.SetTextLabel("foo");

    }

    internal Form1 TheForm {get; private set; }

    public void ThreadForm()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var form1 = new Form1();
        Application.Run(form1);
        TheForm = form1;

    }


}
John M. Wright
  • 4,477
  • 1
  • 43
  • 61