0

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

例如

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

4 回答 4

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时调用。

于 2013-06-26T15:26:53.673 回答
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...
}
于 2013-06-26T15:54:06.960 回答
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...
}
于 2013-06-26T16:14:40.737 回答
-1

我建议lblMinorStatus.Refresh();lblMinorStatus.Text = ....

于 2013-06-26T15:23:49.563 回答