创建一个基于对话框的MFC程序HelloWorld,在CHelloWorldDlg类中新建一个成员函数void InitNotifyIconData(void)。其具体实现如下
void CsupernotepadDlg::InitNotifyIconData(void)
{
/*NOTIFYCONDATA structure contains the information that the system
needs to process taskbar status area message*/
NOTIFYICONDATA nd;
//the size of this structure,in bytes
nd.cbSize = sizeof(NOTIFYICONDATA);
//a handle to the window that receives the notification message associated with an icon in the taskbar status area
nd.hWnd = m_hWnd;
//the application-defined identifier of the taskbar icon
nd.uID = IDR_MAINFRAME;
//Flags that indicate which of the other members contain valid data
nd.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
// is the identifier.The system use it to send notification to the window identified in hWnd
nd.uCallbackMessage = WM_SHELLNOTIFY;
nd.hIcon = m_hIcon;
lstrcpy(nd.szTip,_T("HelloWorld"));
//send the message to the taskbar status area
Shell_NotifyIcon(NIM_ADD,&nd);
}
最后,需要在HelloWorldDlg.h中添加如下代码
#define WM_SHELLNOTIFY (WM_APP + 1)
2.关闭程序时自动清除图标
在类视图中,右击CHelloWorldDlg,选择“属性”(properties),点击“消息”(message),添加WM_ONDESTROY,在生成的OnDestroy函数中填写如下代码
void CHelloWorldDlg::OnDestroy()
{
CDialog::OnDestroy();
// TODO: Add your message handler code here
NOTIFYICONDATA nd;
nd.cbSize = sizeof(NOTIFYICONDATA);
nd.hWnd = m_hWnd;
nd.uID = IDR_MAINFRAME;
//DELETE THE ICON
Shell_NotifyIcon(NIM_DELETE,&nd);
}
3.实现点击最小化按钮时,程序最小化到任务栏
在CHelloWorldDlg类中加载onsize消息(方法同上),
void CHelloWorld::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if( nType = SIZE_MINIMIZED )
{
//hide this window and passes the activition to another window
ShowWindow(SW_HIDE);
}
}