2

I'm implementing a right click menu in an MFC app whose contents are not known until runtime.

While it's simple enough to add menu items to a CMenu object, I haven't figured out a way to handle the messages sent by each menu item.

One technique I was investigating was assigning the same resource ID to each dynamically created menu item and handling all the messages by one callback which would contain the logic to handle each message appropriately. The problem with this approach is that, apart from being kludgey, CMenu menuitem messages are caught using the ON_COMMAND macro which requires a parameterless callback, so no information is passed to it other than than the implicit information that it was called by a resource with a certain resource ID.

I tried to trap the messages using the ON_MESSAGE macro instead as the callbacks it uses receive WPARAM and LPARAM arguments, but the callback is never invoked, so that option seems to be out.

It seems to me that there has to be a way to implement what I'm trying to do but I can't figure out it thus far. Any help is much appreciated.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
ericc
  • 334
  • 1
  • 14

1 Answers1

3

Look at this answer:

https://stackoverflow.com/a/3673672/2287576

As for the message map, assuming all your menu item IDs are within a certain range, you can use ON_COMMAND_RANGE to map the entire range to a single function. This function will receive the ID as a parameter, and within the function, you can perform different operations based on the ID.

Assuming you can set aside a range of ID values this method will work.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • Hi, thanks for the reply. I saw that post elsewhere. Ideally I would like to avoid reserving a range resource IDs, as the menu items represent user created data so I don't know in advance how many they'll need. I may have to go with that approach though as there doesn't seem to be a better way. – ericc Dec 06 '17 at 10:38
  • @ericc Well, thinking realistically here, how many menu items can you practically allow on a user interface? There must be a reasonable limit. Even it you allowed up to a 1000, which I think would be a crazy amount of menu items. This way will work. – Andrew Truckle Dec 06 '17 at 20:08
  • 1
    You're right of course. I've opted to use ON_COMMAND_RANGE as you suggested and so far so good. Thanks ! – ericc Dec 07 '17 at 17:49