繁体   English   中英

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

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

我正在尝试从线程更新form.text。 基本上线程需要用当前时间更新form.text。 我的代码如下所示

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

以及如下方法

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

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

        }
        else
        {
            c.Text = s;
        }
    }

只要主应用程序窗口处于活动状态,代码就起作用。 如果应用程序变为非活动状态,则会出现错误“对象引用未设置为对象的实例”

您正在调用Form1.ActiveForm

ActiveForm :表示当前活动表单的Form;如果没有活动表单,则为null。

如果Form是不活动的,则自然为null 对您的表单使用其他引用。 如果要从表单中调用它,请使用this

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