vb.net:区分me.close()和x-button

时间:2018-04-08 15:24:05

标签: vb.net forms events sender formclosing

如何区分事件,用户明确按下x按钮(或按下ALT F4)以关闭表单以及以编程方式关闭表单的所有其他方法(me.close()等) 。 我已经发现,这可以使用发送者对象来完成,但我并没有真正得到它。有人可以用一个例子向我解释一下吗? 非常感谢你们。

2 个答案:

答案 0 :(得分:1)

FormClosingEventArgs类事件args有一个枚举,用于说明表单关闭的原因。

https://msdn.microsoft.com/en-us/library/system.windows.forms.closereason(v=vs.110).aspx

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.Closing

    If Not appClosing AndAlso e.CloseReason = System.Windows.Forms.CloseReason.UserClosing Then

    ' DO WHATEVER CODE YOU WANT IN HERE
    ' LIKE SETTING E.CANCEL TO TRUE

    End If

End Sub

' You can also set a close appClosing local variable at the class level as a boolean, whenever you call closing in code, assign the variable.
appClosing = True
Me.Close();

答案 1 :(得分:0)

就这么简单。 :)

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
e.Cancel = True
End Sub

这会阻止X按钮关闭表单以及:)。问题是,如果你这样做,你也无法使用Me.Close关闭表单,要解决此问题,只需删除EventHandler:)

  RemoveHandler Me.Closing, AddressOf Form1_FormClosing
  'Now close the form
  Me.Close()