![](/img/trans.png)
[英]C# - Windows 7 taskbar shows AssemblyTitle instead of 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.