我有一个在系统托盘图标中运行的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:我不是程序员,所以请不要苛刻我:)
答案 0 :(得分: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
要停止运行多个应用程序副本,请使用Make Single Instance Application
选项答案 1 :(得分:1)
在您刚刚启动应用程序并测试以前的实例的情况下,我使用了VB End语句来终止该应用程序。
End语句突然停止代码执行,并且不会调用 Dispose或Finalize方法,或任何其他Visual Basic代码。宾语 其他程序持有的引用无效。如果是End语句 在Try或Catch块中遇到,控件未传递给 相应的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
答案 2 :(得分: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 强>