Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right click: menu options

there is a feature I'd like to implement in my application:

The user right clicks on my picturebox object. Good. When that happens, some code of mine executes and will generate a list of options. Then a menu appears where the mouse right-clicked, made up of these options. When the user clicks on one of these options, the menu is deleted and some code is run given the option index as parameter.

My two problems:

  • How can I tell when the user right clicks? I can see an event handler for "click", but that includes left clicks....
  • How do I create one of these menus? I mean, go ahead and right click something. That's the kind of menu I'm looking for.
like image 965
Voldemort Avatar asked Dec 01 '22 03:12

Voldemort


1 Answers

You need to implement the picturebox' MouseUp event. Check if the right button was clicked, then create a ContextMenuStrip with the menu items you want. You can use, say, the Tag property of the items you add to help identify them so you can give them a common Click event handler. Like this:

Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
    If e.Button <> Windows.Forms.MouseButtons.Right Then Return
    Dim cms = New ContextMenuStrip
    Dim item1 = cms.Items.Add("foo")
    item1.Tag = 1
    AddHandler item1.Click, AddressOf menuChoice
    Dim item2 = cms.Items.Add("bar")
    item2.Tag = 2
    AddHandler item2.Click, AddressOf menuChoice
    '-- etc
    '..
    cms.Show(PictureBox1, e.Location)
End Sub

Private Sub menuChoice(ByVal sender As Object, ByVal e As EventArgs)
    Dim item = CType(sender, ToolStripMenuItem)
    Dim selection = CInt(item.Tag)
    '-- etc
End Sub
like image 121
Hans Passant Avatar answered Dec 04 '22 23:12

Hans Passant