我有一个主要为我的表单启动一个线程。我想从主线程更新label1文本。我创建了我的委托和我的方法来更新它,但我不知道如何访问表单线程和修改label1文本。
这里是我的主要代码:
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());
}
}
这里是我的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();
}
}
如何访问表单线程并修改label1文本?我正在使用C#和.Net 4.5。
答案 0 :(得分:1)
您需要在第二个线程上访问Form对象,因此您需要在Program类中公开它。然后,在您的主体中,您应该能够通过暴露的属性进行设置。
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;
}
}