views:

54

answers:

1

I'm writing my own extension. I've created a toolbar button. The template I used was "Visual Studio Package" and there was an option during the wizard to create a command button (or something like that)

So the button shows up, but I can't work out how to get the current document or the selected text within the document.

Any help would be appreciated.

+2  A: 

There are two ways to approach it:

  1. Handle the button globally and use DTE to get the current document (DTE.ActiveDocument) and selected text (((TextDocument)activeDoc).Selection.Text). You can get the top-level DTE object in your package by writing: DTE dte = GetService(typeof(SDTE)) as DTE; Note that the active document may be null.
  2. Create a command handler at the editor level to handle the given command. The Align Assignments extension I wrote (source) is an example of this. Here's what the command filter looks like.
Noah Richards
Thanks, the DTE dte = GetService(typeof(SDTE)) as DTE; was exactly what I was after, I was playing around with the GetService. Is there any resource which lists everything you can pass in to it? and what they all do?
Chris McGrath
One trick is to look for interfaces like `SDTE`; the "S" means "service", and is used as the key for objects stuck in the service provider. Take a look at [this namespace on MSDN](http://msdn.microsoft.com/en-us/library/bb164288.aspx) (scroll the page down until you find the interfaces that start with `SVs`).
Noah Richards
...I should also mention: each of these maps to *at least* one interface, though some can map to many. For example, `SVsUIShell` maps to `IVsUIShell`, `IVsUIShell2`...through 4.
Noah Richards