1

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

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

但我发现(通过设置断点)在某些表单上单击红色 X 时不会调用此事件处理程序,而在其他表单上是。这些表单都是 System.Windows.Forms.Form 类型,但在大多数方面自然是不同的。有谁知道这可能是什么原因以及如何处理?

编辑

在回答 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要设置或清除的任何属性。

4

2 回答 2

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
于 2012-11-05T15:46:59.927 回答
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 关键字添加代码处理程序,而无需使用AddHandlerand RemoveHandler

Protected Sub my_form1_Closing(s as object, e as FormClosingEventArgs) _
    Handles my_form1.Closing
    '...
End Sub
于 2012-11-05T23:12:39.420 回答