分类: C/C++
2008-08-26 15:27:37
This article illustrates the use of Shell_NotifyIcon
to create and manage System Tray icons. The article explains the basics of this operation and assists you in creating your own 'Minimize To Tray' applications. The source code provided with this article is designed to work with dialog-based applications, but it can easily be modified to work with a CFrameWnd
or CWnd
based application.
To create a Tray Icon, you need to call the following shell function: -
BOOL Shell_NotifyIcon( DWORD dwMessage, PNOTIFYICONDATA pnid );
The dwMessage
parameter specifies the action to be taken - NIM_ADD
, NIM_DELETE
, NIM_MODIFY
adds, deletes and modifies tray icons respectively.
The pnid parameter is used to customize, create, delete and obtain data from the Tray Icon. (See the MSDN Library for more details about this structure.)
1. Create a new VC++ dialog based project. For this example, I will call this project MyTray
which will contain the CMyTrayApp
and CMyTrayDlg
classes.
2. Download and extract the DialogTray
source code to the root of the project folder
3. From the Project->Add To Project menu, select Files and then select TrayDialog.h and TrayDialog.cpp. This will add a new class to your project named CTrayDialog
.
4. Replace the CMyTrayDlg
base class with CTrayDialog
.
class CMyTrayDlg : public CDialog
becomes
#include "TrayDialog.h" class CMyTrayDlg : public CTrayDialog
5. Replace the other occurrences of CDialog
in the MyTrayDlg.cpp file as follows :-
CMyTrayDlg::CMyTrayDlg(CWnd* pParent /*=NULL*/) : CDialog(CMyTrayDlg::IDD, pParent)
becomes
CMyTrayDlg::CMyTrayDlg(CWnd* pParent /*=NULL*/) : CTrayDialog(CMyTrayDlg::IDD, pParent)
6. Create a menu resource and name it IDR_MENU1
7. In the InitDialog
member function, enter the following:
TraySetIcon(IDR_MAINFRAME); TraySetToolTip("ToolTip for tray icon"); TraySetMenu(IDR_MENU1);
8. Modify the IDD_MYTRAY _DIALOG
resource to have a minimize box.
9. Build and run the application
NB : To add tray menu item handlers use the class wizard.
Simply add a TrayShow()
statement to InitDialog()
in CMyTrayDlg.cpp, and call TraySetMinimizeToTray(FALSE)
to disable minimizing to the tray.
The events that occur in the tray are captured through the following functions:
virtual void OnTrayLButtonDown(CPoint pt); virtual void OnTrayLButtonDblClk(CPoint pt); virtual void OnTrayRButtonDown(CPoint pt); virtual void OnTrayRButtonDblClk(CPoint pt); virtual void OnTrayMouseMove(CPoint pt);
Feel free to add more events or to improve on these ones.