如何获取 visual studio 2015 editor windows 的选定文本?

How to get selected text of visual studio 2015 editor windows?

我想实现一个 visual studio 2015 扩展来获取用户在代码编辑器中选择的文本。比我想操纵选定的文本。

A​​ 有一个 Button/Command 通过代码编辑器中的上下文菜单。但我不知道如何 获取选定的文本。

我认为这个解决方案 here 已经过时或者我误解了这个解决方案。

我假设您的代码已经在派生自 Package.

的 class 中

您可以像这样获取和修改选择文本:

DTE dte = (DTE)GetService(typeof(DTE));

if (dte.ActiveDocument != null)
{
    var selection = (TextSelection)dte.ActiveDocument.Selection;
    string text = selection.Text;

    // Modify the text, for example:
    text = ">>" + text + "<<";

    // Replace the selection with the modified text.
    selection.Text = text;
}