MFC:程序的托盘显示

介绍

关键技术,API函数Shell_NotifyIcon,具体查看msdn吧

实现的主要代码

#define MY_TRAY_ICON_ID (1)

/
//其他代码:略

BEGIN_MESSAGE_MAP(CTestShowTrayDlg, CDialogEx)
	//...
	ON_MESSAGE(WM_MY_TRAY_ICON, &CTestShowTrayDlg::OnMessageTrayIcon)
	/
END_MESSAGE_MAP()


void CTestShowTrayDlg::ShowTrayIcon()
{
	NOTIFYICONDATA nid = { 0 };
	nid.cbSize = sizeof(NOTIFYICONDATA);
	nid.hWnd = this->m_hWnd;
	nid.uID = MY_TRAY_ICON_ID;
	nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
	nid.uCallbackMessage = WM_MY_TRAY_ICON; //托盘图标中消息回调,如鼠标左键、右键等等
	nid.hIcon = m_hIcon;
	_tcscpy_s(nid.szTip, _T("测试托盘显示图标"));
	Shell_NotifyIcon(NIM_ADD, &nid); //在托盘区添加图标
}

void CTestShowTrayDlg::DelTrayIcon()
{
	NOTIFYICONDATA nid = { 0 };
	nid.cbSize = sizeof(NOTIFYICONDATA);
	nid.hWnd = this->m_hWnd;
	nid.uID = MY_TRAY_ICON_ID;
	Shell_NotifyIcon(NIM_DELETE, &nid); //在托盘区移除图标
}

LRESULT CTestShowTrayDlg::OnMessageTrayIcon(WPARAM wParam, LPARAM lParam)
{
	if (wParam != MY_TRAY_ICON_ID)//wParam传入nid.uID
	{
		return TRUE;
	}

	switch (lParam)
	{
	case WM_LBUTTONUP:
	case WM_LBUTTONDBLCLK:
	{
		OnMenuShowWindow();
		break;
	}
	case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个“关闭”
	{
		CPoint ptCursor;
		::GetCursorPos(&ptCursor);

		//从资源中加载菜单
		CMenu mTrayMenu;
		mTrayMenu.LoadMenu(MAKEINTRESOURCE(IDR_MENU_TRAY));
		CMenu* pMenu = mTrayMenu.GetSubMenu(0);
		if (pMenu) pMenu->TrackPopupMenu(TPM_LEFTALIGN, ptCursor.x, ptCursor.y, this);
		mTrayMenu.DestroyMenu(); //资源回收

		break;
	}
	}
	return TRUE;
}

//显示主界面
void CTestShowTrayDlg::OnMenuShowWindow()
{
	this->ShowWindow(SW_SHOWNORMAL);
	this->SetForegroundWindow();
	this->SetActiveWindow();
}

//退出
void CTestShowTrayDlg::OnMenuExit()
{
	DelTrayIcon();
	CDialogEx::OnCancel();
}


void CTestShowTrayDlg::OnOK()
{
	// TODO:  在此添加专用代码和/或调用基类

	//屏蔽ESC/Enter
	//CDialogEx::OnOK();
}


void CTestShowTrayDlg::OnCancel()
{
	this->ShowWindow(SW_HIDE);
	//屏蔽ESC/Enter
	//CDialogEx::OnCancel();
}

参看

https://www.cnblogs.com/htj10/p/11688347.html

你可能感兴趣的:(Tray,托盘显示)