Tuesday, March 11, 2008

How to minimize application as system tray icon?

Step 1: Add tray icon

void AddIcon()
{
HICON hIcon;

HINSTANCE hInst =
AfxFindResourceHandle(MAKEINTRESOURCE(IDI_MAINFRAME1),
RT_GROUP_ICON);
hIcon = (HICON)LoadImage( hInst,
MAKEINTRESOURCE(IDI_MAINFRAME1),
IMAGE_ICON,
16,
16,
LR_DEFAULTCOLOR);

// Add a Shell_NotifyIcon notificaion
// NOTIFYICONDATA nid;

nid.cbSize = sizeof(NOTIFYICONDATA);
nid.uID = IDI_MAINFRAME1;
nid.uFlags = NIF_ICON;
nid.hIcon = hIcon;
nid.hWnd = m_hWnd; //key here! Otherwise no place to show
nid.uCallbackMessage = WM_TASKBAR;

// Add the notification to the tray.
Shell_NotifyIcon(NIM_ADD, &nid);
}

call AddIcon from OnInitDialog(...)

Step 2: Hide application

this->ShowWindow(SW_HIDE);

Step 3: Handle click event for tray icon:

Form step 1, you notice there is "nid.uCallbackMessage = WM_TASKBAR"

Header file:
// define for WM_TASKBAR (my taskbar message)
#define WM_TASKBAR WM_APP+450

LRESULT OnTaskbar(WPARAM wParam, LPARAM lParam);

Body File:
// function handler for message !!
LRESULT CTestDlg::OnTaskbar(WPARAM wParam, LPARAM lParam)
{
UINT uMouseMsg = (UINT) lParam;
switch (uMouseMsg)
{
case WM_LBUTTONDOWN:
if(!this->IsWindowVisible())
{
this->ShowWindow(SW_SHOW);
this->SetForegroundWindow();
}else
this->ShowWindow(SW_HIDE);
//AfxMessageBox(L"Mouse click on the Icon !");
break;
default: break;
}
return 0;
}

No comments: