tags:

views:

78

answers:

3

how can i make my Form not to close but to Hide when user click on the "X" button on the form?

As i have a NotifyIcon that contain an Exit menu which actually does the Form Closing (i don't want the Form's "X" to close the form but to hide it).

thanks.

+3  A: 

You need to handle Form.Closing event and set e.Cancel to true to stop the form from closing. To hide it call Hide method.

Giorgi
ok, i have set e.Cancel=True but if i wanted to really closed the form then how? like using a menu Exit to close a form.
jameslcs
@jameslcs - Just call Application.Exit() from the toolstrip item click handler and examine e.CloseReason in FormClosing event handler.
Giorgi
+3  A: 

Just implement the FormClosing event. Cancel the close and hide the form unless it was triggered by the notify icon's context menu. For example:

    Private CloseAllowed As Boolean

    Protected Overrides Sub OnFormClosing(ByVal e As System.Windows.Forms.FormClosingEventArgs)
        If Not CloseAllowed And e.CloseReason = CloseReason.UserClosing Then
            Me.Hide()
            e.Cancel = True
        End If
        MyBase.OnFormClosing(e)
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        CloseAllowed = True
        Me.Close()
    End Sub
Hans Passant
thank so much this works!
jameslcs
@Hans - If you just call Application.Exit() from the toolstrip item you do not need CloseAllowed.
Giorgi
Could work, be sure to test e.CloseReason
Hans Passant
nice, i'm changing it to Application.Exit(). thanks for the tip.
jameslcs
+1  A: 
Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = True
        Me.Hide()

End Sub
Jeremy