Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System tray context menu doesn't disappear

I create a notification icon with:

notifyIcon.cbSize = sizeof(NOTIFYICONDATA);
notifyIcon.hWnd   = mainWnd;
notifyIcon.uID    = 100;
notifyIcon.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE;
notifyIcon.hIcon  = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LOGO));
notifyIcon.dwState = NIS_SHAREDICON;
notifyIcon.uVersion = NOTIFYICON_VERSION;
notifyIcon.uTimeout = 15000;
notifyIcon.uCallbackMessage = APP_MSG_TRAY;
wcscpy_s(notifyIcon.szTip, 127, WTXT_APP_TRAY_TOOLTIP);

Shell_NotifyIcon(NIM_ADD, &notifyIcon);
Shell_NotifyIcon(NIM_SETVERSION, &notifyIcon);

And have a context menu popup on WM_RBUTTONDOWN and WM_CONTEXTMENU like this:

MENUITEMINFO separatorBtn = {0};
separatorBtn.cbSize = sizeof(MENUITEMINFO);
separatorBtn.fMask = MIIM_FTYPE;
separatorBtn.fType = MFT_SEPARATOR;

HMENU hMenu = CreatePopupMenu();

if(hMenu) {
 InsertMenu(hMenu, -1, MF_BYPOSITION, APP_OPEN_OPTIONS, WTXT_OPTIONS);
 InsertMenuItem(hMenu, -1, FALSE, &separatorBtn);
 InsertMenu(hMenu, -1, MF_BYPOSITION, APP_MSG_EXIT, WTXT_EXIT);

 POINT pt;
 GetCursorPos(&pt);
 SetForegroundWindow(mainWnd);
 TrackPopupMenu(hMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, mainWnd, NULL);
 PostMessage(mainWnd, WM_NULL, 0, 0);
 DestroyMenu(hMenu);
}

It works fine, but the context menu doesn't disappear always. Sometimes (often) if you have ie. winamp and my app icons in system tray, if you right click my app and winamp afterwards, bot menus will appear, and my menu won't disappear automatically until you click an item.

Any ideas?

thanks...

like image 812
Marin Avatar asked Dec 05 '22 00:12

Marin


1 Answers

To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible).

SetForegroundWindow(hDlg);

TrackPopupMenu(   hSubMenu,
                 TPM_RIGHTBUTTON,
                 pt.x,
                 pt.y,
                 0,
                 hDlg,
                 NULL);
like image 200
Jack Avatar answered Dec 09 '22 15:12

Jack