I have a lengthy context menu and I wanted to add some visual effect to the items (no, I don’t want to make a new renderer), so I just made a MouseEnter and MouseLeave event for one of the list items.
Now I want to extend this to all of the context menu items without making two separate events for each of the items…
Here is a short example of what I have at the moment:
Private Sub NewMenuItems_MouseEnter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewMenuItem1.MouseEnter, NewMenuItem2.MouseEnter, etc.
MenuItem.ForeColor = Color.Red
End Sub
Private Sub NewMenuItems_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewMenuItem1.MouseLeave, NewMenuItem2.MouseLeave
MenuItem.ForeColor = Color.Cyan
End Sub
The only thing that is different for each of the items is what comes before “.Forecolor”.
How do I make this work for all items at the same time?
If all of the instances of
MenuItemare using the same event handlers then you can distinguish which one actually called it using thesenderparameter, which should refer to the instance that invoked the event. So just castsenderto aMenuItemand that’s the one you’re looking for.Note that you should always be careful with casting, of course. In this case you’d want to make sure that it’s only a
MenuItemwhich ever calls this handler, otherwise you’ll want to put in some error checking/handling with the cast in the event that another object invokes it.