我有一个运行在系统任务栏图标中的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/