我正在尝试从一个线程更新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;
}
}
只要主应用程序窗口处于活动状态,代码就会正常工作。如果应用程序变为非活动状态,则会收到错误消息"Object reference not set to an instance of an object“
发布于 2013-02-15 00:33:01
您正在调用Form1.ActiveForm
。
ActiveForm:表示当前活动表单的表单,如果没有活动表单,则为null。
如果Form
处于非活动状态,则这自然是null
。对窗体使用不同的引用。如果要从表单中调用它,请使用this
。
发布于 2013-02-15 00:37:27
将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);
}
https://stackoverflow.com/questions/14879499
复制相似问题