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

标签 vb.net formclosing

我有一个运行在系统任务栏图标中的Windows窗体应用程序。如果用户按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

问题是当我要测试此消息时,会显示该消息,但按ok后,会出现一个新的消息框(该消息来自Private Sub Form_FormClosing)。如果我选​​择“否”,则必须实例运行!
我已经读过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语句。如果您必须使用这些,那么您的应用程序中会有一些问题。

当您想结束应用程序时,请使用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选项

关于vb.net - Vb.net中的Application.Exit()和FormClosing事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886073/

相关文章:

c# - 如何防止使用 alt + F4 关闭任何表单

c# - 如何取消 Hook C# 中的事件处理程序

vb.net - 如何在文本框中只允许数字和点?

vb.net - 如何从 VB.NET 启动 Adob​​e Reader 或 Acrobat?

.net - 即使所有线程都在休眠,多核处理器也会 Hook

vb.net - 具有完整事件的 vb6 上的 Show.net 控件

c# - 如何检测取消 FormClosing 事件的父表单?

c# - 如何防止用户关闭我的 C# 应用程序?

c# - 从某些事件中取消表单关闭

c# - 如何使用 .NET 安装打印机?