Vb.net中的Application.Exit()和FormClosing事件

Ope*_*ust 5 vb.net formclosing

我有一个在系统托盘图标中运行的Windows窗体应用程序.如果用户按下窗口的X按钮,将显示一个消息框,显示是和否(是 - >关闭窗体---否 - >保持窗体运行在系统托盘图标).我正在考虑在用户打开另一个应用程序实例时阻止该场景,因为我已经运行了一个实例,所以我使用了这段代码:

 If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then 
 MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK,
    MessageBoxIcon.Exclamation)
    Application.Exit()
End If
Run Code Online (Sandbox Code Playgroud)

问题是,当我想测试这个消息时,但是在我按下确定后,会出现一个新的消息框(来自Private Sub Form_FormClosing的消息框).如果我选​​择NO,我将不得不运行实例!我已经读过Application.Exit会触发Form_FormClosing事件.

是否有可能取消触发Form_FormClosing事件,或者我做错了什么?

'这是封闭程序

Private Sub Form_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Try
        Dim response As MsgBoxResult
        response = MsgBox("Are you sure you want to exit", CType(MsgBoxStyle.Question + MsgBoxStyle.YesNo, MsgBoxStyle), "Confirm")

        'If the user press Yes the application wil close
        'because the application remains in taskmanager after closing i decide to kill the current process
        If response = MsgBoxResult.Yes Then
            Process.GetCurrentProcess().Kill()
        ElseIf response = MsgBoxResult.No Then
            e.Cancel = True
            Me.WindowState = FormWindowState.Minimized
            Me.Hide()
            NotifyIcon1.Visible = True
        End If
Run Code Online (Sandbox Code Playgroud)

PS:我不是程序员所以请不要苛刻我:)

Mat*_*lko 5

您无需杀死当前进程或使用EndStatement.如果你必须使用这些,那么你的应用程序就会出现问题.

当您想要结束您的应用程序使用时Me.Close.这将触发FormClosing事件:

Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Select Case MessageBox.Show("Are you sure you want to exit?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        Case Windows.Forms.DialogResult.Yes
            'nothing to do here the form is already closing
        Case Windows.Forms.DialogResult.No
            e.Cancel = True 'cancel the form closing event
            'minimize to tray/hide etc here 
    End Select
End Sub
Run Code Online (Sandbox Code Playgroud)

要停止运行多个应用程序副本,请使用"创建单个实例应用程序 "选项