Me.FormClosing适用于某些形式但不适用于其他形式

时间:2012-11-05 15:27:52

标签: vb.net winforms

我希望在我的代码中处理单击表单右上角的红色X的情况。为此我咨询了this并创建了一个事件处理程序: -

Private Sub DoFoo (sender As System.Object, e As System.EventArgs) _
                   Handles Me.FormClosing
    ' Do things
End Sub

但我发现(从设置断点)在某些表单上,当单击红色X时不调用此事件处理程序,而在其他表单上则不会。表单都是System.Windows.Forms.Form类型,但在大多数方面自然是不同的。有谁知道可能导致这种情况的原因以及如何处理它?<​​/ p>

修改

在回答Vitor的问题时,创建了无效的表格: -

If my_form Is Nothing Then
    my_form = New MyForm(parameters)
    my_form.Title = "Contour Plot Options"
Else
    my_form.BringToFront
End If

my_form.Show

那些表现如预期的行为是这样创建的: -

If my_working_form Is Nothing Then
    my_working_form = New MyWorkingForm
End If

my_working_form.Show

我无法在任何地方看到任何Visible属性设置或清除。

2 个答案:

答案 0 :(得分:3)

您的参数不太正确。 FormClosing事件具有FormClosingEventArgs参数:

Private Sub DoFoo(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
                  Handles Me.FormClosing
    If (e.CloseReason = CloseReason.UserClosing) Then

    End If
End Sub

您可以检查属性“CloseReason”的e变量,该属性包括UserClosing枚举,这意味着用户关闭了表单。

每个表单都应该处理自己的FormClosing事件。我没有订阅这个事件,而是最好像这样覆盖它:

Protected Overrides Sub OnFormClosing(ByVal e As FormClosingEventArgs)
  If (e.CloseReason = CloseReason.UserClosing) Then

  End If
  MyBase.OnFormClosing(e)
End Sub

答案 1 :(得分:1)

如果您要实例化表单,则需要记住AddHandler您想要订阅的活动。

my_form = New MyForm(parameters)
my_form.Title = "Contour Plot Options"
AddHandler my_form.Closing, AddressOf MyForm_Closing

'...

Sub MyForm_Closing(s As Object, ByVal e As FormClosingEventArgs)
   '...
End Sub

当然,为了避免内存泄漏,你应该这样做:

'global code
Private myFormClosingEventHandler As FormClosedEventHandler = Nothing
'...

Private Sub CreateForm
    my_form = New MyForm(parameters)
    my_form.Title = "Contour Plot Options"

    myFormClosingEvent = New FormClosedEventHandler(AddressOf MyForm_Closing)
    AddHandler my_form.Closing, myFormClosingEventHandler
    '...
End Sub

Sub MyForm_Closing(s As Object, ByVal e As FormClosingEventArgs)
    RemoveHandler my_form.Closing, myFormClosingEventHandler
   '...
End Sub

或者你可以在课堂上为你做好所有预先准备工作:

Private WithEvents my_form1 As Form = New Form()
Private WithEvents my_form2 As Form = New Form()
'... etc.

现在,您可以像往常一样使用Handle关键字添加代码处理程序,而无需使用AddHandlerRemoveHandler

Protected Sub my_form1_Closing(s as object, e as FormClosingEventArgs) _
    Handles my_form1.Closing
    '...
End Sub