检测关闭表单的所有方法的最佳方法是什么?

时间:2013-02-19 17:06:54

标签: vb.net winforms formclosing

我有一个表单,我在代码中多次使用End关闭。我想在执行此操作时执行命令来保存设置VarsToIni(),它接受​​一些公共变量并将它们保存在INI文件中。我已经尝试将它放在主窗口的FormClosing(它始终保持打开状态)中,这只有在你按下X按钮而不是从End语句中关闭时才有效。

3 个答案:

答案 0 :(得分:2)

添加新的Sub并将调用替换为End,并调用新的Sub:

Sub EndMe()
    VarsToIni()
    Application.Exit() 
End Sub

修改

正如Dan所指出的那样,End()是关闭应用程序的不好方法,首选Application.Exit()

答案 1 :(得分:1)

考虑使用Application.Exit()代替End。这允许FormClosing被调用,无论如何(并且你可以根据它的关闭方式来处理它)。

Private Sub frmMain_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
    Select Case e.CloseReason
        Case CloseReason.ApplicationExitCall
            ' This is the result of Application.Exit()
            e.Cancel = False
        Case CloseReason.UserClosing
            ' This is the result of clicking the red X
            Select Case MessageBox.Show("Are you sure you wish to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                Case DialogResult.Yes
                    e.Cancel = False
                Case DialogResult.No
                    e.Cancel = True
            End Select
        Case Else
            e.Cancel = False
    End Select
    If Not e.Cancel Then
        VarsToIni()
    End If
End Sub

答案 2 :(得分:0)

尽管如此,我对你的问题感到很困惑:
这将关闭所有表格

For each x as Form in My.Application.OpenForms  
'You can then put your VarsToIni() here
 x.Close()
Next

注意:将其添加到导入

Imports System.Windows.Forms