我想知道模块中“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
答案 0 :(得分:7)
每当您创建新表单时:
Dim newForm as Form = New YourFormClass()
AddHandler newForm.FormClosing, AddressOf YourModule.Close
这将通过该子路径发送您想要的所有结束事件。然后,只需删除Handles Me.Closing
,除非您有任何与我们相关的内容使其无关。
答案 1 :(得分:0)
一种可能性是在您的模块中创建一个函数,该函数显示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,您需要在Loading事件中添加Handler,如下所示:
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Me.FormClosing, AddressOf YourModule.AskFormClosing
End Sub
答案 2 :(得分:0)
试试这个。我根据需要更改了工作:
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 Sub
答案 3 :(得分:0)
不是将此代码放在模块中以供重用,而是考虑创建一个具有您希望共享的行为的基础Form
,然后让您拥有其他表单 inherit 来自此基地Form
(而不是来自System.Windows.Forms.Form
)。
请参阅Microsoft网站上的How to: Inherit Windows Forms。