S h o r t S t o r i e s

// Tales from software development

How to set selected text in Visual Studio Extensibility add-ins

leave a comment »

The Visual Studio DTE object implements an ActiveDocument property. If there is an active document then its Selection property will reference a TextSelection instance if the document is a text document. Most of the TextSelection class’s properties are read-only and there are no obvious methods for changing the selection.

My extensibility add-in calls the TextSelection.ReplacePattern() method and when this returns the original text selection has been lost and the last replacement text is now selected. I wanted to restore the original selection but couldn’t find an obvious way to do this. A Google search showed that a lot of other people were hitting the same problem and no one seemed to have found the solution. It doesn’t help that the extensibility framework is not very well documented.

After a few failed attempts I finally worked out how to do it and, as is so often the case, it’s easy when you know how: set the start of the selection by calling the TextSelection.MoveToAbsoluteOffset() method with the Extend argument set to false, and then call it again with the Extend argument set to true to extend the selection to the end of the required selection.

For example:

  if (dte.ActiveDocument != null)
    if (dte.ActiveDocument.Selection != null)
      TextSelection selected = dte.ActiveDocument.Selection as TextSelection;

      if (selected != null)
        if (selected.Text.Length > 0)
          // Save the current selection:
          int selectionStartAbsoluteOffset = selected.TopPoint.AbsoluteCharOffset;
          int selectionEndAbsoluteOffset = selected.BottomPoint.AbsoluteCharOffset;
          // Restore the original selection:
          selected.MoveToAbsoluteOffset(selectionStartAbsoluteOffset, false);
          selected.MoveToAbsoluteOffset(selectionEndAbsoluteOffset, true);




Written by Sea Monkey

November 29, 2012 at 7:28 pm

Posted in Development

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: