如何从另一个表单更改Label的文本?

时间:2010-08-24 02:09:14

标签: c# winforms

这是在c#中完成的windows应用程序中的交叉线程操作,我该如何更改?

4 个答案:

答案 0 :(得分:4)

您可以编写一个可以从任何线程调用的方法:

private void SetLabel(string newText)
{
    Invoke(new Action(() => SomeLabel.Text = NewText));
}

然后你可以从任何线程中调用SetLabel("Update the label, please")

但是,您的问题标题是“从另一个表单”而不是“来自另一个主题”,因此不清楚您的实际含义。如果您只想拥有多个表单,则不需要多线程。您应该仅将线程用于任务,例如下载文件,复制文件,计算值等,但不适用于表单。

答案 1 :(得分:2)

您需要使用委托并调用...

private delegate void SetLabelSub(string NewText);
private void SetLabel(string NewText)
{
 if (this.InvokeRequired()) {
  SetLabelSub Del = new SetLabelSub(SetLabel);
  this.Invoke(Del, new object[] { NewText });
 } else {
  SomeLabel.Text = NewText;
 }
}

然后你可以从任何线程中调用SetLabel("New Text Here")

答案 2 :(得分:1)

如何编写更通用的方法来更改表单中任何控件的Text属性,如:

private void SetText(Control control, string text)
{
    if (control.InvokeRequired)
         this.Invoke(new Action<Control>((c) => c.Text = text),control);
    else
        control.Text = newText; 
}

这适用于来自UI线程或任何其他线程的标签,按钮等。

答案 3 :(得分:0)

如果您正在处理线程,则需要使用表单。Invoke()方法,假设您将表单实例传递给另一个表单。来自

Form form1 = new Form()
Form form2 = new Form();
form2.CallingForm = form1; // make this property or what ever

在form2中添加一些代码,如

form1.Invoke(someDelagate, value);

我不经常使用winforms,但如果你是google form.Invoke你会得到一些关于如何进行跨线程操作的好例子。

相关问题