检测表单何时关闭c#

1

本文介绍了检测表单何时关闭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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14