4

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.

Chris McGrath
  • 1,037
  • 1
  • 11
  • 22

1 Answers1

8

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
  • 6,777
  • 2
  • 31
  • 28
  • 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 Jul 02 '10 at 06:18
  • 1
    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 Jul 02 '10 at 07:09
  • ...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 Jul 02 '10 at 07:11
  • It should be noted that `DTE` only works if there is a `using EnvDTE;` in the header. Same holds true for the `EnvDTE.TextSelection` and other stuff. – Pascal Jul 15 '14 at 12:18