VC实现任务栏托盘

1.定义消息宏

#define WM_TRAYICON_MSG (WM_USER+100)

2.任务栏托盘函数的封装

BOOL CWarEKeyDlg::TrayMyIcon(BOOL bAdd)
{
	BOOL bRet = FALSE;
	NOTIFYICONDATA tnd;
	tnd.cbSize = sizeof(NOTIFYICONDATA);
	tnd.hWnd = m_hWnd;
	tnd.uID = IDR_MAINFRAME;
	if ( bAdd == TRUE ) {
		tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
		tnd.uCallbackMessage = WM_TRAYICON_MSG;//消息响应函数
		tnd.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME));
		_tcscpy_s(tnd.szTip, sizeof(tnd.szTip), _T("WarEkey"));
		bRet = Shell_NotifyIcon(NIM_ADD, &tnd);
	}else{
		ShowWindow(SW_SHOWNA);
		SetForegroundWindow();
		bRet = Shell_NotifyIcon(NIM_DELETE, &tnd);
	}
	return bRet;
}


3.消息响应函数的添加:

ON_MESSAGE(WM_TRAYICON_MSG, OnTrayCallBackMsg)

LRESULT CWarEKeyDlg::OnTrayCallBackMsg(WPARAM wparam, LPARAM lparam)
{
	switch(lparam)
	{
	case WM_RBUTTONUP:
		{
			CMenu mMenu, *pMenu = NULL;
			CPoint pt;
			mMenu.LoadMenu(IDR_MENU);
			pMenu = mMenu.GetSubMenu(0);
			GetCursorPos(&pt);
			SetForegroundWindow();
			pMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, pt.x, pt.y, this);
			break;
		}
	case WM_LBUTTONDBLCLK:
		ShowWindow(SW_RESTORE);
		SetForegroundWindow();
		break;
	default:break;
	}
	return NULL;
}

4.初始化时一般都让其显示任务栏托盘,直到程序结束才将托盘去掉。重载WM_SYSCOMMAND

	if (nID==SC_MINIMIZE)
	{
		ShowWindow(SW_HIDE);
	}
	if (nID==SC_CLOSE)
	{
		TrayMyIcon(FALSE);
		OnClose();
	}



 

你可能感兴趣的:(VC实现任务栏托盘)