Nicholas Tsipanov (nicholas@spbteam.com), September 18, 2002.
Context menu is a very important element of Pocket PC user interface but unfortunatelly this feature is not described enough in helps. This articles explains using context menu in eVC++ applications and gives step-by-step instructions.
How can I use context menu in my dialog or view in MFC based application? Before answering this question I would like to point to the article on Microsoft.com concerning this question, but from my point of view this article is too short and lacks some examples. Here we will tell this story in other words.
To use the context menus in your application create your own control descendant from the control to use. There is a well-known bug in controls behaviour when you use it in other way than creating from template using the design editor. This bug is discussed in article about demonstration of it in CButton class descendants and here we will use similar technique for CListControl.
Creating own class is simple and straightforward:
This is the method to have correct stylus click handling.
At this point you should decide where you want to handle the context menu notification: either the control itself or in its window parent. Both approaches are possible: if you create control that has common menu (i.e. edit control) you could create and track menu in the control's code. Otherwise it could be more convinient to handle this notification in its parent. In both cases you have to add the method OnContextMenu to your handling class:
In this code we have loaded the context menu from the resources. You have to create a menu bar containing one submenu, which will be shown in control.
If you'd like to have menu created on the fly then use the following code to create a menu:
Ensure that you defined IDR_* constants since Visual Studio won't do it for you in this case (but you can use already defined IDs)
Now you can compile the code to see if it works. But it won't, though compiled without errors. What happened? We forget to add the notification handler in the message map: If we add OnContextMenu to control itself our message map will be look like this:
And if you add it to the parent (I mean window parent here, not C++) notification add in this way:
Note that we use ON_NOTIFY instead of ON_NOTIFY_REFLECT macro.
Now its time to handle thse menu entries we added. In simplest case (keep it simple, eh?) - when there are few menu static entries we provide ON_COMMAND handler for each menu entry:
And the handlers have the simple signature:
If you have dynamic menus or want to have one handler for a range of menu items use ON_COMMAND_RANGE macro:
In this case handler receives actual command menu item ID.
Here we used list control for example but you can this approach will work for other controls as well, such as CListBox.
If you want the illustrations in compilable form please download the sample project - ContextMenu.zip (13 Kb).