我想知道模块中'Handles Me.FormClosing‘的任何替代方案。
我已经创建了在单击'X‘按钮时显示确认消息的代码。问题是,我需要将这段代码放到一个模块中,以便在可以调用它的多个窗体上使用,但是,当我尝试这样做时,“Handles Me.FormClosing”将不起作用。
下面是我使用的代码:
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
FrmLogin.Close()
Else
e.Cancel = True
End If
End Sub发布于 2017-08-23 19:05:33
无论何时创建新表单:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.Close这将路由所有您想要的关闭事件通过该潜艇。然后删除Handles Me.Closing,除非您没有向我们展示与之相关的内容。
发布于 2017-08-23 19:17:56
一种可能是在您的模块中创建一个函数,该函数显示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然后添加Handler,如下所示:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.AskFormClosing但对于main-Form,您需要在加载事件中添加处理程序,如下所示:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.FormClosing, AddressOf YourModule.AskFormClosing
End Sub发布于 2017-08-23 19:49:40
尝尝这个。我按照你的要求做了一些改动:
Module YourModule
Public Function AskFormClosing() As Boolean
Dim result As DialogResult = MessageBox.Show("Are you sure you want to Exit the application?", "Exit", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
Return True
Else
Return False
End If
End Function
End Module然后
Private Sub Close(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If YourModule.AskFormClosing Then
Application.Exit
Else
e.Cancel = True
End If
End Subhttps://stackoverflow.com/questions/45837894
复制相似问题