检测表单何时关闭c# [英] Detect when a form has been closed c#

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

问题描述

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

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.

我有一个后台工作程序已启动并正在运行.如果单击 myForm 上的按钮,我还想退出 while(aBackgroundWorker.IsBusy) 循环.

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

现在,在 CustomFormButton_clicked 事件中,我有

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

//CustomForm.cs

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

我是否需要向 CustomForm 类或声明和初始化表单的位置添加更多代码才能检测到闭包?

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?

推荐答案

要检测表单何时真正关闭,需要挂钩 FormClosed 事件:

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
    }

或者:

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆