Loading...
 
JoiWiki » Developer » .Net » .Net Snippets » CSharp Dynamic ContextMenu CSharp Dynamic ContextMenu

CSharp Dynamic ContextMenu

C# Dynamic Context Menu

Context menus are great, they can be attached to a load of objects and give menu items specific to the content of a specific control, you can also attach one context menu to many different controls if they will all need the same menu items and associated methods. But what about looking at the state of the control that called the context menu to determine which items are appropriate and if you've associated a contextmenu to a number of different controls, how can you tell which control triggered the menu to determine this state?

 

There is a solution of course and it's nice and simple, it involves making a context menu in code rather than declaring one on the form and calling the menu builder method using the relevant control's MouseClick event. The only other thing that needs to be done is to create a class that inherits from the ToolStripMenuItem class to add a 'reference object' member for later use. Here's how the code shakes out:

Created by JBaker. Last Modification: Thursday July 4, 2019 11:23:39 BST by JBaker.

Developer