开发者

C# WinForm doesn't close.

开发者 https://www.devze.com 2023-02-16 21:13 出处:网络
开发者_StackOverflow社区I have an application with one main form. In the form I have one object objC of class C. The form gets from objC my control and puts it into panel. The form interacts with objC
开发者_StackOverflow社区

I have an application with one main form. In the form I have one object objC of class C. The form gets from objC my control and puts it into panel. The form interacts with objC through methods calling and subscribing to objC’s events.

When I try to close the form by clicking on [X] button or by calling this.Close(), form isn’t closing. It calls handler of FormClosing. In the handler, I call objC.Dispose(). I checked, there are no exceptions generated. In objC.Dispose() I unsubscribe from all form’s event handlers. And I removed my control from panel with this code:

splitContainerMain.Panel2.SuspendLayout();
{
    splitContainerMain.Panel2.Controls.Clear();
}
splitContainerMain.Panel2.ResumeLayout();

But it just won’t close. I can try to close as many times as I will, FormClosing event will be repeated, but FormClose will be never generated.

This bug is not reproduced when I don't create a control and add it to the panel. What have I done wrong?


There are few explanations for this. But one, you might have a Validating event handler that is canceling the validation. This will also cancel OnFormClosing. Fix:

    void Form1_FormClosing(object sender, FormClosingEventArgs e) {
        e.Cancel = false;
    }

Btw, there is no point in calling Suspend/ResumeLayout, there is no layout done at form closing time. And calling Controls.Clear() does not actually dispose the controls. Rather nasty behavior that trips up a lot of programmers. Best thing to do is to do nothing, parent controls automatically dispose their children controls. And there is no point in unsubscribing events either, the form object and the objC object only reference each other, no other references exist. The garbage collector knows how to handle that.


This question seems to be releated to : Cleaning objects off a form, Where and When? which provides two good alternatives for dealing with your object.

  1. Either dispose of it by implementing the Form's Dispose method or
  2. Simply ensure that the control is added to the System.ComponentModel.IContainer components property of the form. This will ensure that it's dispose method will be called when the form is disposed.
0

精彩评论

暂无评论...
验证码 换一张
取 消