简体   繁体   English

从C#中的线程更新不活动的form.text

[英]updating inactive form.text from a thread in c#

I'm trying to update form.text from a thread. 我正在尝试从线程更新form.text。 Basically thread need to update the form.text with the current time. 基本上线程需要用当前时间更新form.text。 my code looks like below 我的代码如下所示

UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", Form1.ActiveForm);

and the method as below 以及如下方法

    void UpdateText(String s, Control c)
    {
        if (c.InvokeRequired)
        {

            this.BeginInvoke(new MethodInvoker(() => UpdateText(s, c)));

        }
        else
        {
            c.Text = s;
        }
    }

As long as the main application window is active, code works. 只要主应用程序窗口处于活动状态,代码就起作用。 If the application becomes inactive, then I get the error "Object reference not set to an instance of an object" 如果应用程序变为非活动状态,则会出现错误“对象引用未设置为对象的实例”

You are calling Form1.ActiveForm . 您正在调用Form1.ActiveForm

ActiveForm : A Form that represents the currently active form, or null if there is no active form. ActiveForm :表示当前活动表单的Form;如果没有活动表单,则为null。

If the Form is inactive, naturally this would be null . 如果Form是不活动的,则自然为null Use a different reference to your form. 对您的表单使用其他引用。 If you are calling it from within the form, use this . 如果要从表单中调用它,请使用this

Keep the reference of ActiveForm in a private field, and use that field in the Thread ActiveForm的引用保留在私有字段中,并在Thread使用该字段

Control activeControl;
private void start_new_thread()
{
    active = Form1.ActiveForm;
    // start work under thread
}

private void work_under_thread(object state)
{

    //blocking works
    // update here
    UpdateText("My Monitor (Last Updated " + DateTime.Now.ToString("HH:mm:ss tt") + ")", activeControl);

}

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

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