Last Modification: December 11, 1999

How can I handle dynamic menus in MFC?

The problem with handling dynamic menus in MFC is that you obviously can't set up standard menu handlers for them, as you don't know their ID's until runtime. However, there's a simple way to do it: Overriding OnCmdMsg(). By doing this, you get first chance at catching the menu events so you can handle them properly.

In your OnCmdMsg() handler, there are two cases to handle:

  1. When the user selects the item: the nID parameter will have the menu item's id, and nCode == CN_COMMAND.
  2. When the item needs to be updated (enabled/disabled, checked/unchecked):: again, nID will have the menu item's id, nCode == CN_UPDATE_COMMAND_UI and pExtra will point to a CCmdUI object.

That's it! now you've got all you need to handle the menu items.

References  and Samples: