Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMake a program shrink to the system tray when the user clicks the close button in Visual Basic .NET
DescriptionThis example shows how to make a program shrink to the system tray when the user clicks the close button in Visual Basic .NET.
Keywordssystem try, tray, shrink, hide, close, NotifyIcon, VB.NET
CategoriesVB.NET, Controls
 
See Use a System Tray icon in VB.NET for basic information on using the NotifyIcon control to display a context menu in the system tray.

The variable m_CloseOk indicates when the program can close. When the form is about to close, the Closing event handler checks this value to see whether it should allow the close. If is m_CloseOk False, then the event handler cancels the close, hides the form, and sets the tray context menu's ctxTrayShowHide menu command's caption to Show. This happens, for example, if the user clicks the form's close button or presses Alt-F4.

When the user clicks on the tray icon and selects the context menu's Exit command, the program sets m_CloseOk to True and closes the form. The Closing event handler sees that m_CloseOk is True so it allows the form to close.

When the user clicks on the tray icon and selects the context menu's Show or Hide command, the ctxTrayShowHide control's Click event handler executes. If the form is hidden, the code shows it. If the form is visible, the code hides it.

 
Private m_CloseOk As Boolean = False

' Don't close unless m_CloseOk is True.
Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
    As System.ComponentModel.CancelEventArgs) Handles _
    MyBase.Closing
    If Not m_CloseOk Then
        ' The user did not click the context menu's Exit
        ' command.
        ' Shrink to the tray.
        e.Cancel = True
        Me.Hide()
        ctxTrayShowHide.Text = "&Show"
    End If
End Sub

' Close the application.
Private Sub ctxTrayExit_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    ctxTrayExit.Click
    m_CloseOk = True
    Me.Close()
End Sub

Private Sub ctxTrayShowHide_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    ctxTrayShowHide.Click
    If Me.Visible Then
        ' We're visible. Hide.
        Me.Hide()
        ctxTrayShowHide.Text = "&Show"
    Else
        ' We're hidden. Reappear.
        Me.Show()
        ctxTrayShowHide.Text = "&Hide"
    End If
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated