Bob Moore's Coding Tips

21. Why doesn't my context menu dismiss properly when I click elsewhere?

This is a known problem with TrackPopupMenu. The cure is simple, though somewhat obscure. Immediately before you call TrackPopupMenu, make a call to SetForegroundWindow for your menu's owner window. Then immediately after the call to TrackPopupMenu, post the same window a WM_NULL message. Bizarre, but it works. Look at this sample code:

   HMENU hQuick = ::GetSubMenu (m_hUtility, IDM_QUICK);
   POINT CurPos ;
   GetCursorPos (&CurPos);

   SetForegroundWindow (); // Bodge

   TrackPopupMenu (hQuick,
                   TPM_LEFTBUTTON,
                   CurPos.x,
                   CurPos.y,
                   0,
                   GetSafeHwnd(),
                   NULL);

   PostMessage (WM_NULL, 0, 0); // Bodge

Back to tips