Programmatic navigation via context menu in .NET WinForms Framework 2.0
I have a Windows Forms Application written in VB.NET 2.0 framework.
I have a grid that has an associated context menu with the following structure:
MenuItem1
MenuItem2 -->
SubMenuItem1
SubMenuItem2 -->
SubSubMenuItem1
MenuItem3
...
I want to display a context menu when a specific key is pressed inside the grid and select programmatically 'SubMenuItem1'
.
I can display the context menu by calling the Show () method on the context menu item from a grid event KeyUp
like this:
contextMenu.Show(MainForm.GetSingleton(), Cursor.Position)
However, I cannot figure out how to programmatically select an item in a submenu or submenu.
Can anyone please help?
source to share
It might be the biggest ugliest piece of code if someone shows up five minutes later with something like: ToolStripMenuItem8.selectAllParents (). But as far as I could see, there was no such feature.
So here's what I could come up with:
Private Sub openTSMitem(ByVal menu As ContextMenuStrip, ByVal selectitem As ToolStripMenuItem)
'The menu needs to be open befor we call ShowDropDown
menu.Show()
'The list will first contain the parents in the order of bottom to top
'then we will reverse it so we can open the submenus from top to bottom
'otherwise it will not open them all
Dim parentsRevOrder As ArrayList = New ArrayList()
'Add the parents to the list
Dim parentItem As ToolStripMenuItem = selectitem.OwnerItem
While Not parentItem Is Nothing
parentsRevOrder.Add(parentItem)
parentItem = parentItem.OwnerItem
End While
'reverse the list. now its in the order top to bottom
'and the submenus will open correctly
parentsRevOrder.Reverse()
'now loop through and open the submenus
For Each tsiParent As ToolStripMenuItem In parentsRevOrder
tsiParent.ShowDropDown()
Next
'and finally select the menuItem we want
selectitem.Select()
End Sub
And then call sub:
openTSMitem(ContextMenuStrip1, ToolStripMenuItem8)
Hope it helps.
Edit: I just saw that the comments and code are a bit messed up in the answer, just paste it into Visual Studio and it should look just fine.
source to share