使用活动的GUI更新处理应用关闭事件

时间:2013-06-26 15:18:06

标签: c# winforms events

我正在开发一个WinForms C#应用程序,该应用程序具有一些可能长时间运行的清理活动。我想在单击关闭按钮后在清理活动中显示用户状态更新,但似乎不会在FormClosing()事件中处理对GUI的任何更新。

e.g。

private void MyApp_FormClosing(object sender, FormClosingEventArgs e)
{
    lblMainStatus.Text = "Closing app, please wait.";
    foreach(MyResource r in AppResources)
    {
        lblMinorStatus.Text = "Freeing resources - remaining : " + AppResources.Count;
        r.discard();
    }
    lblMinorStatus.Text = "Done.";
    // And so on...
}

有什么想法吗?我唯一能想到的是删除窗口上的“X”关闭按钮,而是关闭应用程序中的菜单项或自定义关闭按钮,但我更希望保持标准关闭按钮处于活动状态。 提前谢谢。

4 个答案:

答案 0 :(得分:0)

你应该强迫.Refresh()确保标签是最新的。但是,如果你在退出时做了很多事情,你可以做这样的事情(不是在VS的计算机上所以请检查拼写错误等未编译检查):

private bool _applicationReadyToExit = false;

// ... Your project code here ...

private void MyApp_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!_applicationReadyToExit)
    {
        e.Cancel = true;
        CleanAndExit();
        return;
    }
}

private void CleanAndExit()
{
    lblMainStatus.Text = "Closing app, please wait.";
    lblMainStatus.Refresh();

    foreach(MyResource r in AppResources)
    {
        lblMinorStatus.Text = "Freeing resources - remaining : " + AppResources.Count;
        lblMinorStatus.Refresh();
        r.discard();
    }
    lblMinorStatus.Text = "Done.";
    lblMinorStatus.Refresh();

    // And so on... Then close informing that we are clean
    _applicationReadyToExit = true;
    this.Close();
}

这样,您可以通过菜单或按钮点击等来调用CleanAndExit(),以及用户点击X时。

答案 1 :(得分:0)

有些控件会在FormClosing时更新,有些则不会。 在需要的时候,在表单上调用Refresh可能最容易,因为所有控件都应该更新。

private void MyApp_FormClosing(object sender, FormClosingEventArgs e)
{
  lblMainStatus.Text = "Closing app, please wait.";
  MyApp.Refresh();

  foreach(MyResource r in AppResources)
  {
    lblMinorStatus.Text = "Freeing resources - remaining : " + AppResources.Count;
    r.discard();
    MyApp.Refresh();
  }

  lblMinorStatus.Text = "Done.";
  MyApp.Refresh();
  // And so on...
}

答案 2 :(得分:0)

一种方法是代替您提供消息框的标签,或者您可以这样做......

private void MyApp_FormClosing(object sender, FormClosingEventArgs e)
{
    lblMainStatus.Text = "Closing app, please wait.";
    foreach(MyResource r in AppResources)
    {
        System.Threading.Thread.Sleep(1000);
        lblMinorStatus.Text = "Freeing resources - remaining : " + AppResources.Count;
        r.discard();
        this.Refresh();
    }
    lblMinorStatus.Text = "Done.";
    // And so on...
}

答案 3 :(得分:-1)

我建议在lblMinorStatus.Refresh();之后添加lblMinorStatus.Text = ...