c# - 无法更新 Windows 窗体中的状态栏文本
问题描述
在我的 Windows 窗体应用程序中,我试图更新状态栏上的文本,但无法这样做。这是我的代码:
public void CreateMyStatusBar(string msg = "Ready")
{
StatusBar statusBar1 = new StatusBar();
this.Invoke(new Action(() =>
{
statusBar1.Text = msg;
statusBar1.Update();
}));
statusBar1.Invalidate();
statusBar1.Refresh();
statusBar1.Update();
Form1.gui.Controls.Add(statusBar1);
}
public static Form1 gui;
Form1 是我的主要表单,gui在 Form1.cs中定义。
每当我打电话
CreateMyStatusBar("ABC")
函数它显示第一次调用时发送给它的文本。但是当再次调用此函数时,文本不会更新。
我浏览了类似this和this的各种帖子并开始编写上面的代码,但它似乎不起作用。谁能告诉我哪里出了问题或者我必须做些什么来解决这个问题?
解决方案
每次更新文本时不要创建新的状态栏
StatusBar statusBar1 = null;
public void CreateMyStatusBar(string msg = "Ready")
{
if(statusBar1 == null) {
statusBar1 = new StatusBar();
Form1.gui.Controls.Add(statusBar1);
}
this.Invoke(new Action(() =>
{
statusBar1.Text = msg;
statusBar1.Update();
}));
statusBar1.Invalidate();
statusBar1.Refresh();
statusBar1.Update();
}
编辑:改用 this.Controls.Add 有帮助吗?
public partial class Form1 : Form
{
StatusBar statusBar1 = null;
public Form1()
{
InitializeComponent();
this.Shown += new System.EventHandler(this.Form1_Shown);
}
public void CreateMyStatusBar(string msg = "Ready")
{
if (statusBar1 == null)
{
statusBar1 = new StatusBar();
this.Controls.Add(statusBar1);
}
if (InvokeRequired)
{
this.Invoke(new Action(() =>
{
statusBar1.Text = msg;
statusBar1.Update();
}));
}
else
{
statusBar1.Text = msg;
}
statusBar1.Invalidate();
statusBar1.Refresh();
statusBar1.Update();
}
private void Form1_Shown(object sender, EventArgs e)
{
CreateMyStatusBar("one");
System.Threading.Thread.Sleep(5000);//Wait - and blocks UI :(
CreateMyStatusBar("two");
}
}
推荐阅读
- paypal - 是否有使用 REST API V2 的 PayPal SDK
- google-chrome - Chrome 扩展网页检查器
- mysql-workbench - 连接失败 - AWS RDS 和 mySQL Workbench
- android - 如果我在本地存储和检索数据,是否需要后台线程?
- asp.net-mvc - 单个 MVC APP 中的 Azure AD 和身份框架
- php - 自定义 Woocommerce 电子邮件:获取产品缩略图和价格
- python - 调用特定函数的函数列表
- java - 是不是不可能在后台有一个代码,每 24 小时都会调用一次?
- kotlin - 在 kotlin 中从 GSON 生成对象时不调用数据类初始化函数
- c - 练习使用 strace 确定源代码行为