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).
So whats the solution?
Simple. Just call the function on the window receiving the menu messages before JUST before you call TrackPopupMenu() or TrackPopupMenuEx().
TrackPopupMenuEx(hMenu, ..., x, y, m_hwnd, ...);