Programming/MFC

Example : Icon in Tray

부풍 2009. 8. 27. 15:37

stdafx.h

#define WM_TRAY_NOTIFYING (WM_USER + 10)

CMainFrame

private:
	NOTIFYICONDATA m_nid;

Tray Icon 생성

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	// ~~~~
 
	HICON hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
 
	m_nid.cbSize = sizeof(NOTIFYICONDATA);
	m_nid.hWnd = m_hWnd;
	m_nid.uID = IDR_MAINFRAME;
	m_nid.hIcon = hIcon;
	m_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
	m_nid.uCallbackMessage = WM_TRAY_NOTIFYING;
	strcpy(m_nid.szTip, "Tray Icon Testing");
 
	Shell_NotifyIcon(NIM_ADD, &m_nid);
 
	return 0;
}

Tray Icon 제거

void CMainFrame::OnClose()
{
	Shell_NotifyIcon(NIM_DELETE, &m_nid);
 
	if (m_nid.hIcon)
		DestroyIcon(m_nid.hIcon);
 
	CFrameWnd::OnClose();
}

Tray Icon 클릭

Message Map

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	ON_WM_CREATE()
	ON_WM_CLOSE()
	ON_MESSAGE(WM_TRAY_NOTIFYING, OnTrayNotifying)
END_MESSAGE_MAP()

선언 (MainFrm.h)

	afx_msg LONG OnTrayNotifying(WPARAM wParam, LPARAM lParam);

Action (MainFrm.cpp)

LONG CMainFrame::OnTrayNotifying(WPARAM wParam, LPARAM lParam)
{
	if (lParam == WM_RBUTTONUP) {
		//AfxMessageBox("OOPS!!! Right mouse button clicked.");
 
		CMenu *pMenu, *pPopup;
		pMenu = GetMenu();
		pPopup = pMenu->GetSubMenu(0);
 
		CPoint pos;
		GetCursorPos(&pos);
 
		SetForegroundWindow();
 
		pPopup->TrackPopupMenu(TPM_LEFTALIGN|TPM_RIGHTBUTTON, pos.x, pos.y, this, NULL);
 
		PostMessage(WM_NULL);
	}
	return 0;
}