检测表单何时被关闭c#

检测表单何时被关闭c#

本文介绍了检测表单何时被关闭c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WinForm,我创建一个按钮显示一个提示。这是一个自定义的WinForm视图,因为消息框对话框不够。



我有一个后台工作器启动并运行。如果myForm上的按钮被点击,我也想退出while( aBackgroundWorker.IsBusy )循环。

  // MyProgram.cs 

using(CustomForm myForm = new CustomForm())
{
myForm.Show(theFormOwner);
myForm.Refresh();

while(aBackgroundWorker.IsBusy)
{
Thread.Sleep(1);
Application.DoEvents();
}
}

现在,在 CustomForm Button_clicked 事件,我有

  // CustomForm.cs 

private void TheButton_Click(object sender,EventArgs e)
{
this.Close();
}

我需要在CustomForm类中添加更多的代码,我声明并初始化表单以便能够检测到一个闭包?

解决方案

要检测表单何时被关闭,你需要钩住FormClosed事件:

  this.FormClosed + = new FormClosedEventHandler(Form1_FormClosed); 

void Form1_FormClosed(object sender,FormClosedEventArgs e)
{
//做某事
}

或者:

  using(CustomForm myForm = new CustomForm 
{
myForm.FormClosed + = new FormClosedEventHandler(MyForm_FormClosed);
...
}

void MyForm_FormClosed(object sender,FormClosedEventArgs e)
{
//做某事
}


I have a WinForm that I create that shows a prompt with a button. This is a custom WinForm view, as a message box dialog was not sufficient.

I have a background worker started and running. I also want to exit the while(aBackgroundWorker.IsBusy) loop if the button on myForm was clicked.

//MyProgram.cs

using(CustomForm myForm = new CustomForm())
{
    myForm.Show(theFormOwner);
    myForm.Refresh();

    while(aBackgroundWorker.IsBusy)
    {
        Thread.Sleep(1);
        Application.DoEvents();
    }
}

Right now, in the CustomForm the Button_clicked event, I have

//CustomForm.cs

private void theButton_Click(object sender, EventArgs e)
{
  this.Close();
}

Do I need to add more code to the CustomForm class, or the location where I declare and initialize the form in order to be able to detect a closure?

解决方案

To detect when the form is actually closed, you need to hook the FormClosed event:

    this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);

    void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        // Do something
    }

Alternatively:

using(CustomForm myForm = new CustomForm())
{
    myForm.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
    ...
}

void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
    // Do something
}

这篇关于检测表单何时被关闭c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:19