I have one application for windows forms that runs in the icon in the system tray. If the user clicked the X button of the window, a message appears with the message “Yes” and “No” (“Yes” → close the form --- No-> save the form launched in the system tray icon). I thought to prevent the scenario when the user opens another instance of the application when the instance is already running, so I used this code:
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
The problem is that when I want to test this message, a message is displayed, but after I click OK, a new message box will appear (this is from Private Sub Form_FormClosing). If I select NO, I will have to run the instance! I read that Application.Exit fires the Form_FormClosing event.
Is there any way to cancel the launch of the Form_FormClosing event, or am I something wrong?
'this is a form closing procedure
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: I am not a programmer, so please do not be harsh with me :)
source
share