How to know which dynamically-created menu item is clicked

Hello:

I am dynamically creating an “Open Recent Files” sub-menu. The submenu items get added just fine and I have a single MenuHandler Event defined. Here’s the code that works:

var recentfiles As DesktopMenuItem = Me.MenuBar.Child("FileMenu").Child("FileRecentFiles")
var mnu As DesktopMenuItem

for itm As Integer = fileNames.Count -1 to 0 step -1
  mnu = New DesktopMenuItem(fileNames(itm), itm)
  mnu.Name = "mnuRecent"
  recentfiles.AddMenu(mnu)
next

Question:

The MenuHandler event does fire when any of the submenu items are clicked, however I don’t know which one was selected. I was thinking I could use the tag property that I’m setting on the NewDesktopMenuItem line (above), but clearly I’m not doing something correctly.

What am I missing here?

You can examine the Text property of the MenuItem, or its tag.

In the context of opening a Recent File, it would be common practice to store the FolderItem corresponding to the file in the tag and just call App.Open on it in the MenuHandler.

You need to subclass DesktopMenuItem and handle the events there.

Fortunately, I don’t have hair because I would have pulled it all out by now until I realized that it needed to be subclassed.

1 Like

In REALbasic, Real Studio and original Xojo, the Event had an Index Property (the clicked MenuItem). I remember having asked this question in this Forum, but…

Oh Wow!

That made sense as well.

usually the menu item have a tag property where you can place any thing a name or number or a class object.
a tag name is better then a index because if you add more items the index could move.

Constructor
DesktopMenuItem(text As String, tag As Variant)