我有一个学校的VB项目。当用户尝试关闭表单时,我必须创建一个YesNo样式的消息框。如果用户按“是”,则应用程序关闭;如果用户按“否”,则返回程序屏幕。问题是,当我按“否”时,应用程序仍然关闭,我不知道VB是否有故障,但它显示两个消息框。我是VB的新手(上个月开始)。这是代码:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim closing As MsgBoxResult
closing = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question,)
If closing = MsgBoxResult.Yes Then Application.Exit()
End Sub
答案 0 :(得分:2)
关闭已经开始时发生FormClosing
事件。
您需要取消结束,而不是致电Application.Exit
。
Application.Exit
的调用再次触发结束事件。因此,MessageBox出现两次。
如果e.Cancel = True
的结果为MessageBox
,请设置No
:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) = MsgBoxResult.No Then
e.Cancel = True
End If
End Sub
答案 1 :(得分:0)
由于您处于Form.Closing事件中,除非您致电e.Cancel = True
,否则表单将会关闭。
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim closing As MsgBoxResult
closing = MsgBox("Are you sure you want to exit?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question,)
If closing = MsgBoxResult.No Then
e.Cancel = True
End If
End Sub