MFC实现电脑托盘效果
2023-05-25
15
0
初始化代码
增加拖盘效果,添加图标,这里用我们程序自带的ICO ID,IDR_MAINFRAME,也可以自添加。
添加我们拖盘时的右键菜单
m_menu.LoadMenu(IDR_MENU_TRAY);
//在OnInitDialog方法中调用
NOTIFYICONDATA data;
data.cbSize = sizeof(NOTIFYICONDATA);//结构体的大小
data.hWnd = this->m_hWnd;//接收托盘消息的窗口句柄 this是当前dialog
data.uID = IDR_MAINFRAME;//定义的托盘图标ID
data.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;//设置属性,下面的三个属性是否有效
lstrcpyn(data.szTip, _T("单击右键显示菜单"), sizeof(_T("单击右键显示菜单")));//图标上的提示字符串
data.uCallbackMessage = WM_ONTRAY;//自定义的消息,
data.hIcon = ::LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));//显示在系统托盘上的图标
Shell_NotifyIcon(NIM_ADD, &data);// 向任务栏的状态栏发送添加托盘图标的消息
添加自定义消息
#define WM_ONTRAY WM_USER+1
使用类向导添加消息处理函数
BEGIN_MESSAGE_MAP(CTestDlg, CDialogEx)
...
ON_MESSAGE(WM_ONTRAY, &CTestDlg::OnTray)
ON_COMMAND(IDM_SHOW_UI, &CTestDlg::OnShowUi) //菜单响应
ON_COMMAND(IDM_EXIT_APP, &CTestDlg::OnExitApp) //菜单响应
END_MESSAGE_MAP()
实现消息响应函数:
LRESULT CTestDlg::OnTray(WPARAM wParam, LPARAM lParam)
{
UINT uMouseMsg = (UINT)lParam;
if (uMouseMsg == WM_RBUTTONDOWN)
{
CMenu* pPopup = m_menu.GetSubMenu(0);
CPoint point;
GetCursorPos(&point);
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_VERTICAL,
point.x, point.y, AfxGetApp()->m_pMainWnd, TPM_LEFTALIGN);
}
else if (uMouseMsg == WM_LBUTTONDBLCLK)
{
this->ShowWindow(SW_SHOW);
}
return 0;
}
关闭消息HOOK
点击X退出时的消息过滤,在OnSysCommand中添加如下:
void CTestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else if (nID == SC_MINIMIZE)//最小化,把他隐藏起来
{
this->ShowWindow(SW_HIDE);
}
else if (nID == SC_CLOSE)//最小化,把他隐藏起来
{
this->ShowWindow(SW_HIDE);
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
程序退出时清理
当程序退出时会出现拖盘图标不清空的现象,可以在退出函数中增加如下代码:
void CTestDlg::OnShowUi()
{
SendMessage(WM_SYSCOMMAND, SC_RESTORE, 0);
}
void CTestDlg::OnExitApp()
{
NOTIFYICONDATA nd;
nd.cbSize = sizeof(NOTIFYICONDATA);
nd.hWnd = m_hWnd;
nd.uID = IDR_MAINFRAME;
Shell_NotifyIcon(NIM_DELETE, &nd);
SendMessage(WM_CLOSE, 0, 0);
}
参考:https://blog.51cto.com/xiaohaiwa/5891182