我有一个主线程,用于为表单启动线程。我想从主线程更新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。
您需要访问第二个线程上的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;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句