Application.Exit() and FormClosing event in Vb.net

Operagust picture Operagust · Mar 27, 2012 · Viewed 57.1k times · Source

I have a single windows form application that is running in system tray icon.If the user press X button of the windows form a messagebox is displayed with Yes and No ( Yes ->close the form---No->keep the form running in system tray icon). I was thinking to prevent the scenario when the user open another instance of the application when there is already an instance running so i have 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 the message is displayed but after i press ok, a new messagebox appears (that one from Private Sub Form_FormClosing ).If i choose NO i will have to instance running! I have read that Application.Exit fires the Form_FormClosing event.

Is there any possibility to cancel the triggering of the Form_FormClosing event,or am i doing something wrong?

'this is the formclosing 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 don't be to harsh with me:)

Answer

Matt Wilko picture Matt Wilko · Mar 27, 2012

You don't need to Kill the current process or use the End Statement. If you have to use these then there is something amiss with your application.

When you want to end your application use Me.Close. This will fire the FormClosing event:

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

To stop more than one copy of your application from running use the option to Make Single Instance Application