Many .Net component verndor requires to add global context menu command to Visual Studio, which should be available whenever a required
DesignerHost (Windows Forms, Web Forms, User Control etc. ) with corresponding form is active. However, .Net framework doesn't provide any method to add global context menu command permanently.
AddVerb() method boasts to add global verb. But it is actually specific to the Component, for which
IMenuCommandService is used. Whenever selection of control changes to something else, the verb is lost. I have developed a hack to introduce this capability flawlessly into .Net framework.
When I was developing my winforms layout manager Called 'SmartLayouts', I had exactly this requirement. I required it because I needed to provide ease of use to my users for layouting task. A toolbutton, Menu Command could do it, but it looks hassle in long term to users. After several days of intense research I found the trick of creating global verb which stays in Context Menu of desired
As global level commands has to be visual studio plugin to be activated with visual studio startup, my solution too is a Visual Studio plug-in.
For Adding the Verb, you first need to ensure that correct
DesignerHost is loaded. This is ensured by Comparing
System.Windows.Forms.Form (you can use others according to your requirement). After that, We get
ISelectionService sel = host.RootComponent.Site.GetService(typeof(ISelectionService)) as ISelectionService;
We attach an
ISelectionService.SelectionChanged. That event handler is the crux of the hack. Whenever Selection changes, the eventHandler executes to Add the required verb back to
IMenuCommandService verb list. The event handler containes code similar to following.
IMenuCommandService mcs = host.RootComponent.Site.GetService(typeof(IMenuCommandService)) as IMenuCommandService;
Now, the result is that you get the desired Verb whenever selection changed to designer of any other component. Overall, whenever you right click, you have the desired command in context menu!
The source code of sample project is given. However, you need to add the
in your addin folder(usually in My Documents\Visual Studio 2005\Addins) and edit its xml node <assembly> to point to real ContextMenuCommand.dll.
<Assembly>C:\Documents and Settings\vkhaitan\My Documents\Visual Studio 2005\Projects\ContextMenuCommand\ContextMenuCommand\bin\ContextMenuCommand.dll</Assembly>
All the Documents and Source code are supplied with license The Code Project Open License (CPOL).
It would have been better, if .Net framework provided method for this and we didn't need to resort to these hacks. However, in practice, I found that this hack works flawlessly and never shown me any kind of problem or bug. So you can use it whenever you need it.