5

我有一个在系统托盘图标中运行的窗体应用程序。如果用户按下窗体的 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 的那个)。如果我选​​择否,我将不得不实例运行!我已阅读 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:我不是程序员,所以请不要对我苛刻:)

4

3 回答 3

5

您不需要终止当前进程或使用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

要停止运行多个应用程序副本,请使用“制作单实例应用程序”选项

于 2012-03-27T10:30:57.400 回答
1

在您刚刚启动应用程序并正在测试以前的实例的情况下,我使用了VB End语句来终止应用程序。

End 语句突然停止代码执行,并且不调用 Dispose 或 Finalize 方法或任何其他 Visual Basic 代码。其他程序持有的对象引用无效。如果在 Try 或 Catch 块中遇到 End 语句,则控制不会传递到相应的 finally 块。

If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length> 1 Then  
   MessageBox.Show("Another instance is running", "Error Window", MessageBoxButtons.OK,         MessageBoxIcon.Exclamation) 
   End
End If 
于 2012-03-27T09:00:01.377 回答
1
Private Sub main_master_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing 
If e.CloseReason = CloseReason.UserClosing Then
'Put you desired Code inside this! 
Msgbox("Application Closing from Taskbar") 
End If 
End Sub

它将从任务栏关闭exe或终止进程。如果用户从任务栏关闭应用程序。

CloseReason.UserClosing 

如果用户从 Taskber关闭应用程序,事件将关闭应用程序

于 2014-04-15T06:56:34.357 回答