【问题标题】:Access Ui Control from an other thread [duplicate]从另一个线程访问 Ui Control [重复]
【发布时间】:2020-08-10 21:05:27
【问题描述】:

所以我想从另一个线程中另一个类中的静态方法访问主窗体中的标签

我该怎么做?

顺便说一句,我用这段代码来启动线程

 new Thread(new ThreadStart(WebHelper.Check)).Start();

【问题讨论】:

  • 你不应该。移动数据,而不是控件。

标签: c# .net multithreading winforms


【解决方案1】:

UI 只能由 UI 线程更改。如果您的线程与表单在同一个类中,您可以使用Control.Invoke 方法访问 UI 线程。

this.Invoke(new Action(() => {
    //UI Code here
}));

但是,如果你想从另一个类访问它,我建议使用events 访问 UI 的类,然后你可以使用 Invoke。

//This would be in your class
public delegate void UIStuff(string text);
class AClass
{
    public static event UIStuff ChangeLabel;

    public static void StaticFunction() {
         ChangeLabel.Invoke("Test");
    }
}
//This would be your form class
public partial class Form1 : Form
{
    public Form1(){
        AClass.ChangeLabel += AClass_ChangeLabel; //Note you can press tab for auto complete
    }
    AClass_ChangeLabel(string text) {
        this.Invoke(new Action(() => {
            this.MainLabel = text;
        }));
    }
}

注意:我相信你也可以通过在静态方法Form1 f1 = new Form1(); 中创建一个新实例来更改标签,但我不相信这就是你想要的。

【讨论】:

  • 请将链接页面中的重要细节直接放在您的答案中。不鼓励将链接作为问题的内容。
  • 我正在关注你的回答,如果你能改进它,我很乐意投票。
猜你喜欢
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 2021-02-15
  • 1970-01-01
相关资源
最近更新 更多