如何在vb.net中处理表单关闭事件

时间:2011-04-27 14:00:02

标签: vb.net winforms

我使用了以下代码,但没有显示msgbox。这段代码有什么问题?

Private Sub frmSimple_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
       Dim result = MsgBox("Are you sure you want to Exit ?", vbYesNo)
       If result = DialogResult.Yes Then
        me.Close()
       End If
End Sub

7 个答案:

答案 0 :(得分:14)

此代码在表单关闭后处理时运行 根据您显示表单的方式,它可能根本不会被处理掉。

如果您要取消关闭,则需要处理FormClosing事件并将e.Cancel设置为True

答案 1 :(得分:6)

  Private Sub frmProgramma_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If MessageBox.Show("Are you sur to close this application?", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
    Else
      e.Cancel = True
    End If
  End Sub

或者这就是我每次都一遍又一遍地使用它......

答案 2 :(得分:3)

使用FormClosing事件。 MSDN

答案 3 :(得分:3)

 Dim result = MsgBox("Are you sure you want to Exit ?", vbYesNo)

       If result = vbYes Then
        me.Close()
       End If

答案 4 :(得分:2)

If MessageBox.Show("¿Exit?", "Application, MessageBoxButtons.YesNo, _
                        MessageBoxIcon.Question) = DialogResult.No Then
            e.Cancel = True
        End If

答案 5 :(得分:1)

我觉得它更简洁干净!

If MsgBox("Are you sure you want to Exit ?", vbYesNo) = vbNo Then e.Cancel = True

答案 6 :(得分:0)

此代码可能不是“高效”的,但允许用户在关闭之前保存其工作;如果按下“否”,则关闭表单;如果按下“取消”,则返回到表单而不关闭。

        Dim dialog As DialogResult
        dialog = MessageBox.Show("Save before closing?", "Exit", MessageBoxButtons.YesNoCancel)
        If dialog = DialogResult.Yes Then
            'Put a save file dialog here or Button.PerformClick() if you already have a save button programmed
        ElseIf dialog = DialogResult.No Then
            Application.Exit()
        ElseIf dialog = DialogResult.Cancel Then
            e.Cancel = True
        End If