Extending the Visual Studio 2010 editor by adding a context menu item to manipulate selected text

Andy West picture Andy West · Jun 5, 2011 · Viewed 10.2k times · Source

I'd like to create an extension to Visual Studio that will allow someone to select any text in an editor, right-click to get a context menu, and then perform some action on the text by clicking on my custom menu item.

Let's say for example that my custom menu item is called "Email...". The new context menu for the editor might look something like this:

Breakpoint
Run to Cursor
Cut
Copy
Paste
Email...
Outlining

I'd also like to add a popup (adornment?) with options. In this case it could be things like To, Subject, and CC fields.

I think that some of this can be done with MEF using editor extensions, like the popup and the actual code for firing off an email. But it looks like I need a VSPackage to add the context menu item. From what I've read, I can bundle the MEF piece and the VSPackage together.

This is where I get stuck. I need an in-depth reference with details to implement both parts, but I also need information on how to integrate them. MSDN has me going around in circles.

Is there any good, solid example code or documentation (even books) that I can learn from?

Answer

gameweld picture gameweld · Mar 18, 2012

1) You can create always get a reference to EnvDTE in an extension.

m_dte = (EnvDTE.DTE)this.GetService(typeof(EnvDTE.DTE));

2) To directly add, menu item in the extension paradigm. You just need to modify the ".VSCT" file. First, the menu command is defined in a menu group. In the VSCT file, the group definition looks like this as generated:

<Group guid="guidCodeBlogCmdSet" id="MyMenuGroup" priority="0x0600">
<Parent guid="guidSHLMainMenu" id="IDM_VS_MENU_TOOLS"/>
</Group>

To move the “Email” menu entry to the context menu, all we need to do is specify the code window context editor as the parent for the menu group, using the identifier IDM_VS_CTX_CODEWIN:

<Group guid="guidCodeBlogCmdSet" id="MyMenuGroup" priority="0x0600">
<Parent guid="guidSHLMainMenu" id="IDM_VS_CTXT_CODEWIN"/>
</Group>

I based this example from a neat tutorial on how to auto-tweet or blog an code snippet from visual studio: http://solutions.developer.com/ms/web-dev/visual-studio/codeblog-writing-a-blogging-extension-for-visual-studio-2010.html