简体   繁体   English

从单独的线程和类访问WinForms控件

[英]Accessing WinForms Control from separate thread and class

I have a class named "tables", and a winform "Form1", on the form is a button called "table3". 我有一个名为“ tables”的类,一个winform为“ Form1”,在窗体上是一个名为“ table3”的按钮。 The code in the "tables" class runs in a separate thread and needs access to the button on the main form, this is what I have: “表”类中的代码在单独的线程中运行,需要访问主窗体上的按钮,这就是我所拥有的:

Form1.ActiveForm.BeginInvoke(
(Action)(() =>
{
    Form1.ActiveForm.Controls["table3"].Text = "test";
}));

I'm getting a null reference exception.. The name of the button is correct. 我收到一个null引用异常。按钮的名称正确。 there's some other problem and I'm not sure what it could be :/ 还有其他问题,我不确定这可能是什么:/

Try this: 尝试这个:

Invoke(new Action<object>((args) =>
{
    Form1.ActiveForm.Controls["table3"].Text = "test";
}));

If you're getting a NullReferenceException, then a reference is null. 如果您收到NullReferenceException,则引用为null。 So either Form1.ActiveForm == null , or Form1.ActiveForm.Controls == null , or Form1.ActiveForm.Controls["table3"] == null . 因此,要么Form1.ActiveForm == null ,要么Form1.ActiveForm.Controls == null ,或者Form1.ActiveForm.Controls["table3"] == null

I assume Form1 is the name of the class and ActiveForm is a static property. 我假设Form1是类的名称,而ActiveForm是静态属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM