如果单击“是”,则显示MessageBox并退出应用程序的模块中可能会创建一个函数,否则返回False
。
Module YourModule
Private dontAskAgain As Boolean
Public Function AskFormClosing() As Boolean
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
End If
End If
Return dontAskAgain
End Function
End Module
然后你只需要设置e.Cancel
给函数的求反结果。
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = Not YourModule.AskFormClosing
End Sub
如果你喜欢使用的AddHandler其他人的建议,你可以用下面的方法,这将导致同样的结果。
Module YourModule
Public Sub AskFormClosing(sender As Object, e As FormClosingEventArgs)
If dontAskAgain = False Then
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
dontAskAgain = True
Application.Exit()
Else
e.Cancel = True
End If
End If
End Sub
End Module
然后添加处理程序是这样的:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.AskFormClosing
但你的主表格,您将需要添加的处理程序中加载事件,像这样:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.FormClosing, AddressOf YourModule.AskFormClosing
End Sub
使用[AddHandler](https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/addhandler-statement) – Pikoh