很多程序都可以缩小到电脑的右下角变成一个图标,这个就是在程序中添加托盘消息,添加的步骤如下:
1.在XXXdlg.h中添加托盘函数的void toTray();
2.在XXXdlg.cpp中写函数定义:
void CXXXDlg::toTray()
{
NOTIFYICONDATA nid;
nid.cbSize=(DWORD)sizeof(NOTIFYICONDATA);
nid.hWnd=this->m_hWnd;
nid.uID=IDR_MAINFRAME;
nid.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP ;
nid.uCallbackMessage=WM_SHOWTASK;//自定义的消息名称
nid.hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME));
strcpy(nid.szTip,"123456"); //信息提示条为“123456”
Shell_NotifyIcon(NIM_ADD,&nid); //在托盘区添加图标
ShowWindow(SW_HIDE); //隐藏主窗口
}
3.在void CXXXXDlg::OnSize(UINT nType, int cx, int cy) 中添加最小化时调用托盘程序
{
CDialog::OnSize(nType, cx, cy);
if(nType==SIZE_MINIMIZED)
toTray();
// TODO: Add your message handler code here
}
4.在stdafx.h中增加#define WM_SHOWTASK WM_USER + 108 //托盘消息影射的宏定义
5..在XXXdlg.h中添加LRESULT onShowTask(WPARAM wParam,LPARAM lParam);
6.在XXXdlg.cpp的消息映射表中ON_MESSAGE(WM_SHOWTASK,onShowTask):
7.在XXXdlg.cpp中添加函数定义:
LRESULT CWlqnjnDlg::onShowTask(WPARAM wParam,LPARAM lParam)
//wParam接收的是图标的ID,而lParam接收的是鼠标的行为
{
if(wParam!=IDR_MAINFRAME)
return 1;
switch(lParam)
{
case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个“关闭”
{
LPPOINT lpoint=new tagPOINT;
::GetCursorPos(lpoint);//得到鼠标位置
CMenu menu;
menu.CreatePopupMenu();//声明一个弹出式菜单
//增加菜单项“关闭”,点击则发送消息WM_DESTROY给主窗口,将程序结束。
//menu.AppendMenu(MF_STRING,WM_DESTROY,"退出");
//menu.AppendMenu(MF_STRING, this->ShowWindow(SW_SHOW),"还原");
//确定弹出式菜单的位置
menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x,lpoint->y,this);
//资源回收
HMENU hmenu=menu.Detach();
menu.DestroyMenu();
delete lpoint;
//鼠标右键单击弹出菜单
/* CMenu menu;
menu.LoadMenu(IDR_MENU);
//载入事先定义的菜单
CMenu* pMenu=menu.GetSubMenu(0);
CPoint pos;
GetCursorPos(&pos);
pMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON,pos.x,pos.y,AfxGetMainWnd());*/
}
break;
case WM_LBUTTONDBLCLK://双击左键的处理
{
//this->ShowWindow(SW_SHOW);//简单的显示主窗口完事儿
AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOW);
AfxGetApp()->m_pMainWnd->ShowWindow(SW_RESTORE);
::SetForegroundWindow(this->m_hWnd);
}
break;
}
return 0;
}
来实现鼠标双击托盘图标的消息。
8.添加ON_WM_DESTROY()消息响应
void CWlqnjnDlg::OnDestroy()
{
NOTIFYICONDATA tnid;
tnid.cbSize = sizeof(NOTIFYICONDATA);
tnid.hWnd = m_hWnd;
tnid.uID = IDR_MAINFRAME;
//用NIM_DELETE删除图标
Shell_NotifyIcon(NIM_DELETE, &tnid);
CDialog::OnDestroy();
// TODO: Add your message handler code here
}