C# 刷新窗口窗体,即使不是活动窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14476988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refresh a windows form, even when not the active window
提问by Mark
I am trying something quite basic.
我正在尝试一些非常基本的东西。
I have 3 labels on my windows form, which I would like to populate from 3 separate queries from the database, but also to show the user that something is happening, I would like to show each label as the data is available from the respective query.
我的 Windows 窗体上有 3 个标签,我想从数据库中的 3 个单独查询中填充它们,但也向用户显示正在发生的事情,我想显示每个标签,因为数据可从相应的查询中获得.
To do this, I can use:
为此,我可以使用:
Form.ActiveForm.Refresh();
However, if the user clicks on any other window on their desktop, that command fails, with the "object not set" error.
但是,如果用户单击桌面上的任何其他窗口,该命令将失败,并显示“未设置对象”错误。
Is there any way that I can refresh the labels on the Form, even if the form window is not the active window?
有什么方法可以刷新表单上的标签,即使表单窗口不是活动窗口?
// Breach within next hour
DataTable tbBreach = (get info from database)
tbBreach.DefaultView.Sort = "Assignee ASC";
dgBreach.DataSource = tbBreach;
lbBreach2.Text = tbBreach.Rows.Count.ToString();
Form.ActiveForm.Refresh(); //Would like to update this form field now, and show it on the form
// Breach within next 24 hour
DataTable tbBreach24 = (get info from database)
tbBreach24.DefaultView.Sort = "Assignee ASC";
dgBreach24.DataSource = tbBreach24;
lbBreach24.Text = tbBreach24.Rows.Count.ToString();
Form.ActiveForm.Refresh();
Thank you,
谢谢,
Mark
标记
采纳答案by digEmAll
The labels will be refreshed automatically at the end of the elaboration.
标签将在细化结束时自动刷新。
You probably want to force the refresh to update labels in the middle of the elaboration and you can do that simply using this.Refresh()
since I suspect the method is located inside the form class.
您可能希望在精化过程中强制刷新以更新标签,您可以简单地使用,this.Refresh()
因为我怀疑该方法位于表单类中。
However, when you have a long elaboration and you need to keep the UI updated and reactive (i.e. not frozen) the suggested approach is to avoid elaboration on the UI thread, but to delegate the work on another thread using a BackGroundWorker
.
但是,当您进行长时间的细化并且需要保持 UI 更新和反应性(即不冻结)时,建议的方法是避免在 UI 线程上进行细化,而是使用BackGroundWorker
.
Here'sa working example of BackGroundWorker usage.