Show a Linked Context Menu Generically

Problem

You want to show context menus for multiple controls with a minimum amount of code.

Solution

Write a generic event handler that retrieves the context menu that is associated with a control.

Discussion

You can associate a control with a context menu by settings the control’s ContextMenu property. However, this is only a convenience—in order to display the context menu, you must retrieve the menu and call its Show method, supplying both a parent control and a pair of coordinates. Usually, you implement this logic in an event handler for the MouseDown event.

The good news is that the logic for showing context menus is completely generic, no matter what the control is. Every control supports the ContextMenu ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.