Tuesday, January 20, 2009

Using Notify Icon in Visual Basic 2005


To add notify icon to system tray is much easier in VB2005 than VB6. Create a new Windows Application in VB2005. Add NotifyIcon control as shown in the following figure.


Select "NotifyIcon1" control. In its properties window, choose "Icon" and open your icon to be used. If you do not define an icon there, you will not see notify icon in the system tray.
To display the notify icon when you close your application, go to code view and enter the following code to FormClosing event.

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing        
          If MessageBox.Show("Do you really want to exit?", "Exit", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.No Then            
                e.Cancel = True           
                Me.Visible = False
                NotifyIcon1.Visible = True
          End If        
    End Sub 

To display the application back when you double click the notify icon in the system tray, write the following code in MouseDoubleClick event of NotifyIcon1 control.

Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
          Me.Visible = True ' Show the form.
          Me.Activate() ' Activate the form.
          NotifyIcon1.Visible = False
End Sub

To close the application also from File menu and context menu. Add these controls.


Then add the code 'Me.Close()' to their click event so that it becomes ...

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
          ' Close the form, which closes the application.
          Me.Close()
End Sub

Private Sub ContextMenuStrip1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ContextMenuStrip1.Click
          Me.Close()
End Sub

Select NotifyIcon1 control and define the ContextMenuStrip1 control in its ContestMenuStrip property so that the pop up menu will appear when you right click on the notify icon.

After that you can run the program. When you close the window, a message box will appear to confirm that you really want to exit. If you choose "No", the application will remain in the system tray on which you can double click to call back the application.

No comments:

Post a Comment

Comments are moderated and don't be surprised if your comment does not appear promptly.