首页 > 解决方案 > 无法更新 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")

函数它显示第一次调用时发送给它的文本。但是当再次调用此函数时,文本不会更新。

我浏览了类似thisthis的各种帖子并开始编写上面的代码,但它似乎不起作用。谁能告诉我哪里出了问题或者我必须做些什么来解决这个问题?

标签: c#winformsstatusbar

解决方案


每次更新文本时不要创建新的状态栏

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");
    }
}

推荐阅读