Search code examples
vb.netcolorspictureboxcontextmenustrip

Use ContextMenuStrip to change property of specific control, in vb.net


I have a relatively simple problem, I have a form with 3 pictureboxes, all I wish to do is make it so that you can change the color of a picturebox to either; Red, Amber or Green using a contextmenustrip. So they rightclick on the box and select a color.

So far however, I haven't been able to find anything useful apart from the following,

  Private Sub ContextMenuStrip1_Click(sender As Object, e As EventArgs) Handles ContextMenuStrip1.Click
   Dim cms As ContextMenuStrip = CType(sender, ContextMenuStrip)
   Dim Item = cms.SourceControl.Name
  End sub

But I can't seem to link it to the specific control to then change its color.

Sorry if this doesn't make much sense, I will try to reword it if neccessary. Thanks in advance.


Solution

  • I'm assuming that you've already created the contextMenuStrip.

    In the designer, click on the picture box that you want to add the context menu to.

    Do the same for the other picture boxes.

    In the properties down on the right hand side of your Visual Studio window, scroll to the line that says ContextMenuStrip, click the button at the end of that line and your ContextMenuStrip name should be in the dropdown list. Click it and you should be good to go.

    To handle the menu item click you'd use something like the code below - changing its name and the event handler to match whatever your menu item is called.

      Private Sub RedToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RedToolStripMenuItem.Click
        Dim pBox As PictureBox = CType(ContextMenuStrip1.SourceControl, PictureBox)
        pBox.BackColor = Color.Red
    End Sub
    

    The code above determines which PictureBox opened the contex menu and changes its BackColor property to Red.