我有一个单独的 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 
 问题是,当我想测试这个消息时,但是在我按下确定后,会出现一个新的消息框(来自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 
 PS:我不是程序员所以请不要苛刻我:)
您无需杀死当前进程或使用End Statement.如果你必须使用这些,那么你的应用程序就会出现问题.如果要结束应用程序,请使用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 
 要停止运行多个应用程序副本,请使用选项Make Single Instance Application
