问题描述
我有一个主窗体的应用程序。在窗体我有C类的一个对象objC的形式从objC得到我的控制,并将其放入面板中。形式通过打电话和订阅objC的事件的方法与objC交互。
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.
当我尝试通过单击[X]按钮或致电this.Close(关闭窗体),形式不打烊。它调用的FormClosing的处理程序。在处理程序,我称之为objC.Dispose()。我查了一下,有没有产生的异常。在objC.Dispose()我所有窗体的事件处理程序退订。我打消了我的控制,从使用此代码面板:
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();
但就是不敢靠近。我可以尝试关闭很多次我会的FormClosing事件会反复,但FormClose将永远不会发生。
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.
当我没有这个bug是不是转载创建一个控制并把它添加到面板。我做了什么错?
This bug is not reproduced when I don't create a control and add it to the panel. What have I done wrong?
推荐答案
这有一些解释。但一个,你可能有被取消验证一个验证事件处理程序。这也将取消OnFormClosing。修复:
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;
}
顺便说一句,有呼吁暂停/ ResumeLayout没有意义,也没有布局在表格截止时间完成。并调用Controls.Clear()实际上并不处置控制。相当恶劣的行为的,也让很多程序员。做的最好的事情就是什么都不做,父控件自动处理自己的孩子控制。并且在退订的事件没有任何点,表单对象和objC对象只相互引用,引用不存在。垃圾收集器知道如何处理这个问题。
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.
这篇关于C#的WinForm不会关闭。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!