SteinSOFT.net
  Using Popup menus with Mfc

This short code snippet will explain the most important things about using popup menus in your Mfc applications. This is indeed one of the most easiest tasks of the Mfc class library. The first step involves creating a popup menu. If you are using Visual C++ you simply have to create a new menu resource using the resource editor. As example I will assume IDR_CONTEXT as our popup menu. Note that a popup menu only has one submenu and the text of the top item won't have any influence later on.

Next thing to do is to handle the Windows message WM_CONTEXTMENU. This message can be handled by any class that is derived from CWnd like CView or CDialog. Visual C++ can do all these message handle things for you. Here's the actual code:

void CTestView::OnContextMenu(CWnd* pWnd, CPoint point) 
{ 
   //our menu
   CMenu contextMenu; 
   //the actual popup menu which is the first
   //sub menu item of IDR_CONTEXT
   CMenu* tracker; 

   //at first we'll load our menu
   contextMenu.LoadMenu(IDR_CONTEXT); 
 
   //we have to translate the mouse coordinates first:
   //these are relative to the window (or view) but the context menu
   //needs coordinates that are relative to the whole screen
   ClientToScreen(&point);
 
   //tracker now points to IDR_CONTEXT's first submenu 
   //GetSubMenu(0) -> returns the first submenu,
   // GetSubMenu(1)-> second one etc..
   tracker = contextMenu.GetSubMenu(0); 

   //show the context menu
   tracker->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, 
      point.x , point.y , AfxGetMainWnd()); 

   //has always to be called (function of base class)
   CTestView::OnRButtonDown(nFlags, point); 
} 

I think the code is pretty much self-explaining. You should see that using a popupmenu is not really complicated. Note that we could also have handled the message WM_RBUTTONDOWN when the right mousson button is pressed but it wouldn't be called when the Windows special key on the keyboard is pressed, like with WM_CONTEXTMENU.

If you have questions or suggestions, take a look at the message board. Happy Coding in the meantime!

Copyright © by SteinSOFT