FormClosing和FormClosed事件不起作用

Jea*_*ean 6 c# forms events

我正在开发一个C#应用程序,并且我需要在用户关闭表单之前进行一些验证。

我尝试使用该FormClosing事件,但是没有用,后来我使用了该FormClosed事件,但是相同。

问题是,当我单击“关闭按钮”(位于表单顶部)时,它什么也没做,但是我在表单属性中拥有所有事件。

在此处输入图片说明 在此处输入图片说明

这是我的代码:

    private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
    {
    //things I have to do
    //...
    //...

    if(bandera==true)
    Application.Exit();

    }
Run Code Online (Sandbox Code Playgroud)

    private void Inicio_FormClosed_1(object sender, FormClosingEventArgs e)
    {
    //things I have to do
    //...
    //...

    if(bandera==true)
    Application.Exit();

    }
Run Code Online (Sandbox Code Playgroud)

任何的想法?

谢谢

var*_*bas 5

这两个事件都应该正常工作。只需打开一个新项目并进行这个简单的测试:

 private void Form1_Load(object sender, EventArgs e)
 {
     this.FormClosing += new FormClosingEventHandler(Inicio_FormClosing_1);
     this.FormClosed += new FormClosedEventHandler(Inicio_FormClosed_1);
 }

 private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
 {
     //Things while closing

 }

 private void Inicio_FormClosed_1(object sender, FormClosedEventArgs e)
 {
     //Things when closed
 }
Run Code Online (Sandbox Code Playgroud)

如果在这些方法中设置断点,您会看到在单击关闭按钮后到达它们。您的事件附加代码中似乎存在一些问题。例如:Inicio_FormClosed_1(object sender, FormClosingEventArgs e)是错误的,只要它需要一个FormClosedEventArgs论点;因此,此方法肯定与 无关FormClosed event(否则,代码将无法编译)。


Jea*_*ean 5

我发现了错误;

这里:(当我初始化表单时)

    public Inicio()
    {
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoScroll = true;

        this.ClientSize = new System.Drawing.Size(635, 332);
        this.StartPosition = FormStartPosition.CenterScreen;
        llenaForm(nombreFormulario);
        Application.EnableVisualStyles();

    }
Run Code Online (Sandbox Code Playgroud)

我所需要的只是: InitializeComponent();
我误删了

它应该是:

    public Inicio()
    {
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoScroll = true;`

        InitializeComponent();//<<<<<<<<------------------- 

        this.ClientSize = new System.Drawing.Size(635, 332);
        this.StartPosition = FormStartPosition.CenterScreen;
        llenaForm(nombreFormulario);
        Application.EnableVisualStyles();
    }
Run Code Online (Sandbox Code Playgroud)

十分感谢大家!