Creating tray application and popup context menu in Windows

If you want to add your application in system tray and popup a context menu

#include<windows.h>
#include "resource.h"

HINSTANCE g_hInstance;
const int WM_EX_MESSAGE = (WM_APP + 1);

BOOL TrayIcon(HWND hWnd, HICON hIcon, DWORD msg)
{
NOTIFYICONDATA nid;
ZeroMemory(&nid,sizeof(NOTIFYICONDATA));
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = hWnd;
nid.uID = IDI_ICON2;
nid.uFlags = NIF_TIP | NIF_ICON | NIF_MESSAGE;
nid.uCallbackMessage = WM_EX_MESSAGE;
nid.hIcon = hIcon;
lstrcpyn(nid.szTip, __TEXT("This is my tray app!"), 64);
return Shell_NotifyIcon(msg,&nid);
}

void ContextMenu(HWND hwnd)
{
HMENU hmenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(IDR_MENU2));
HMENU hmnuPopup = GetSubMenu(hmenu,0);
SetMenuDefaultItem(hmnuPopup,IDOK,FALSE);
POINT pt;
GetCursorPos(&pt);
TrackPopupMenu(hmnuPopup,TPM_LEFTALIGN,pt.x,pt.y,0,hwnd,NULL);
DestroyMenu(hmnuPopup);
DestroyMenu(hmenu);
}

BOOL CALLBACK APP_DlgProc(HWND hDlg, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch(uiMsg)
{
case WM_EX_MESSAGE:
if(wParam==IDI_ICON2)
{
switch(lParam)
{
case WM_LBUTTONUP:
ContextMenu(hDlg);
break;
}
}
break;
}

return FALSE;
}

// the IDI_ICON2 is the ID of the icon added to the project

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPTSTR lpCmdLine, int nShowCmd)
{
g_hInstance = hInstance;
HICON hSmallIcon = reinterpret_cast(LoadImage(hInstance, MAKEINTRESOURCE(IDI_ICON2), IMAGE_ICON, 32,22,0));
HWND hDlg = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1),NULL, APP_DlgProc);
TrayIcon(hDlg, hSmallIcon, NIM_ADD);

MSG msg;
while(GetMessage(&msg,NULL,0,0))
{
if(!IsDialogMessage(hDlg,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

TrayIcon(hDlg, hSmallIcon, NIM_DELETE);
DestroyWindow(hDlg);
DestroyIcon(hSmallIcon);
return 1;
}

Comments

Popular posts from this blog

How to statically link applications to wxWidgets via Visual Studio 2008 and in Linux

How to put an image to wxPanel using wxWidgets