MFC添加图标到托盘

Posted greenleaf1976

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MFC添加图标到托盘相关的知识,希望对你有一定的参考价值。

MFC窗口实现最小化到托盘 右键菜单和还原

//.h文件
void toTray();//最小化到托盘
void DeleteTray();//删除托盘图标

afx_msg LRESULT OnShowTask(WPARAM wParam,LPARAM lParam) ;//图标恢复

//.cpp文件

define WM_SHOWTASK (WM_USER +1)

define IDR_SHOW 11

define IDR_OTHER 12

define IDR_EXIT 13

BEGIN_MESSAGE_MAP()
...
ON_MESSAGE(WM_SHOWTASK,OnShowTask)//消息映射
END_MESSAGE_MAP()

void ScheduleDlg::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,"OA");//信息提示条为“OA”?
??? Shell_NotifyIcon(NIM_ADD,&nid);//在托盘区添加图标?
??? ShowWindow(SW_HIDE);//隐藏主窗口
}

LRESULT ScheduleDlg::OnShowTask(WPARAM wParam, LPARAM lParam)
{//wParam接收的是图标的ID,而lParam接收的是鼠标的行为
??? if(wParam != IDR_MAINFRAME) return 1;
??? switch (lParam)
??? {
??? case WM_LBUTTONUP://左键单击显示主界面
??????? {
??????????? this->ShowWindow(SW_SHOW);
??????????? SetForegroundWindow();
??????????? DeleteTray();
??????? }break;
??? case WM_RBUTTONUP://右击弹出菜单
??????? {
??????????? LPPOINT lpoint = new tagPOINT;
??????????? ::GetCursorPos(lpoint);//得到鼠标位置
??????????? CMenu menu;
??????????? menu.CreatePopupMenu();
??????????? menu.AppendMenu(MFT_STRING, IDR_SHOW, "打开主界面");
??????????? menu.AppendMenu(MFT_STRING, IDR_OTHER, "其他");
??????????? menu.AppendMenu(MFT_STRING, IDR_EXIT, "退出");
??????????? SetForegroundWindow();
??????????? EnableMenuItem(menu,IDR_OTHER,MF_GRAYED);//"其他"菜单变灰
??????????? //menu.TrackPopupMenu(TPM_LEFTALIGN, lpoint->x,lpoint->y,this);//显示菜单
??????????? int xx=TrackPopupMenu(menu,TPM_RETURNCMD,lpoint->x,lpoint->y,NULL,this->m_hWnd,NULL);//显示菜单并获取选项ID
??????????? if(xx==IDR_SHOW)
??????????? {
??????????????? this->ShowWindow(SW_SHOW);
??????????????? SetForegroundWindow();
??????????????? DeleteTray();
??????????? }
??????????? else if(xx==IDR_OTHER) {MessageBox("你点击了“其他”菜单","提示",MB_OK);}
??????????? else if(xx==IDR_EXIT) {OnBnClickedCancel();}
??????????? HMENU hmenu = menu.Detach();
??????????? menu.DestroyMenu();
??????????? delete lpoint;
??????? }break;
??? case WM_LBUTTONDBLCLK:
??????? {
??????????? //双击不处理
??????? }break;
??? }
??? return 0;
}

void ScheduleDlg::DeleteTray()//销毁托盘图标
{
??? 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,"OA");
??? Shell_NotifyIcon(NIM_DELETE, &nid);
}

以上是关于MFC添加图标到托盘的主要内容,如果未能解决你的问题,请参考以下文章

Ownerdrawn托盘图标(winapi)?

Qt设置系统托盘图标和程序图标

MFC C++ 托盘应用程序问题

MFC 任务托盘经常消失问题

winform最小化到托盘,托盘右击菜单显示

OSX 上的 QT:托盘图标 - 图标 Dock 问题