捕获 ac# 表单上的关闭事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/537453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:15:47  来源:igfitidea点击:

Catching the close event on a c# form

c#forms

提问by AntonioCS

Hey! I am not trying to push my luck here but I have another c# question. I have tried every possible event I found using google. Here is the code:

嘿!我不想在这里碰运气,但我还有另一个 c# 问题。我已经尝试了使用谷歌找到的所有可能的事件。这是代码:

 private void Form1_OnClose()
        {
            MessageBox.Show("I was closed -2");
        }

        private void Form1_Exit(object sender, EventArgs evArgs)
        {
            MessageBox.Show("I was closed -1");         
        }
        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            MessageBox.Show("I was closed 0");
        }     

        private void Form1_Closed(object sender, EventArgs e)
        {
            MessageBox.Show("I was closed 1");
        }
        private void Form1_FormClosed(Object sender, FormClosedEventArgs e)
        {

            MessageBox.Show("I was closed 2");
        }

Not one of these trigger anything when I either do Alt+f4 or click on the X button. What am I doing wrong here?

当我执行 Alt+f4 或单击 X 按钮时,这些都不会触发任何事情。我在这里做错了什么?

采纳答案by Anton Gogolev

You might be missing actual subscription code, which is something along these lines:

您可能缺少实际的订阅代码,大致如下:

this.Closing += Form1_Closing;

Instead, try overriding OnXXXmethods - this is the preferred way of doing things.

相反,尝试覆盖OnXXX方法 - 这是首选的处理方式。

回答by Misko

Are these methods actually assigned as event handlers? Go to design mode, select the form, then click the little lightning bolt above the properties window. Then find the event you want (Closing probably) and double click it.

这些方法实际上被分配为事件处理程序吗?进入设计模式,选择窗体,然后单击属性窗口上方的小闪电。然后找到您想要的事件(可能关闭)并双击它。

回答by Chris Holmes

The error is likely that you aren't wiring the events at the right time. Check your program.cs file. It should look something like this:

错误很可能是您没有在正确的时间连接事件。检查您的 program.cs 文件。它应该是这样的:

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace Test
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Form form = new Form2();
            form.Closing += form_Closing;
            Application.Run(form);
        }
        private static void form_Closing(object sender, CancelEventArgs e)
        {
            MessageBox.Show("Closing");
        }
    }
}

I just ran this and the event fired.

我刚刚运行了这个,事件就被触发了。