Hide/close menu when mouse is clicked outside its focus

menu, winapi

Solution

Read the Remarks at the bottom of the docs for the `TrackPopupMenu` function: http://msdn.microsoft.com/en-us/library/windows/desktop/ms648002(v=vs.85).aspx

Specifically:

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). If the current window is a child window, you must set the (top-level) parent window as the foreground window.

Problem

I have a legacy code in which WIn 32 programming is done. In here, there's a tray icon which launches a menu when right clicked on. However, the menu persists even when clicked outside its focus area. How do I close the menu when I mouse click in some other place? Frameworks like Qt manage it fine enough. Do I have to keep track of the mouse pointer, capture the click and see whether it falls outside the menu area? Code is in legacy C, and no object oriented concepts are used..so not like I can override something here. Kindly advise, thanks.

Original source