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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5805335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:28:09  来源:igfitidea点击:

How to handle a form close event in vb.net

vb.netwinforms

提问by Failed_Noob

I have used the below code but its not showing the msgbox. What is wrong with this code ?

我使用了下面的代码,但它没有显示 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

回答by SLaks

This code runs after the form has been closed, when it's being disposed.
Depending on how you're showing the form, it might not get disposed at all.

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

You need to handle the FormClosingevent and set e.Cancelto Trueif you want to cancel the close.

您需要处理该FormClosing事件并设置e.CancelTrue是否要取消关闭。

回答by ProblemAnswerQue

  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

or that is how i use it everytime over and over...

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

回答by Hyman

Use FormClosingevent. MSDN

使用FormClosing事件。MSDN

回答by Sivashankar

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

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

回答by CLAUDIO

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

回答by Filippo

I think it is more clean and simply!

我认为它更干净,更简单!

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

回答by Josh Face

This code may not be 'efficient' but allows the user to save their work before closing, close the form if they press 'No' or return back to the form without closing if they press 'Cancel'.

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

        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