获取编辑器窗口的选定文本。视觉工作室扩展

时间:2010-05-19 18:06:43

标签: c# visual-studio

您正在为visual studio制作扩展程序,我需要的具体内容是获取编辑器窗口的选定文本以供进一步处理。有人知道有什么接口或服务吗? 以前我需要找到开放解决方案的路径,为此我要求一个实现IVsSolution的服务,所以对于这个其他问题,我必须有一些服务能够为我提供这些信息。

2 个答案:

答案 0 :(得分:11)

为了澄清Stacker的答案中的“只是获取视图主机”,下面是完整的代码,介绍如何从Visual Studio 2010 VSPackage中的任何其他位置获取当前编辑器视图,以及ITextSelection。特别是,我用它来从菜单命令回调中获取当前选择。

IWpfTextViewHost GetCurrentViewHost()
{
    // code to get access to the editor's currently selected text cribbed from
    // http://msdn.microsoft.com/en-us/library/dd884850.aspx
    IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
    IVsTextView vTextView = null;
    int mustHaveFocus = 1;
    txtMgr.GetActiveView(mustHaveFocus, null, out vTextView);
    IVsUserData userData = vTextView as IVsUserData;
    if (userData == null)
    {
        return null;
    }
    else
    {
        IWpfTextViewHost viewHost;
        object holder;
        Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
        userData.GetData(ref guidViewHost, out holder);
        viewHost = (IWpfTextViewHost)holder;
        return viewHost;
    }
}


/// Given an IWpfTextViewHost representing the currently selected editor pane,
/// return the ITextDocument for that view. That's useful for learning things 
/// like the filename of the document, its creation date, and so on.
ITextDocument GetTextDocumentForView( IWpfTextViewHost viewHost )
{
    ITextDocument document;
    viewHost.TextView.TextDataModel.DocumentBuffer.Properties.TryGetProperty(typeof(ITextDocument), out document);
    return document;
}

/// Get the current editor selection
ITextSelection GetSelection( IWpfTextViewHost viewHost )
{
    return viewHost.TextView.Selection;
}

以下是MSDN的IWpfTextViewHostITextDocumentITextSelection文档。

答案 1 :(得分:3)

OnlayoutChanged内部,以下代码会弹出一条包含所选代码的消息:

if (_view.Selection.IsEmpty) return;
else
{
    string selectedText = _view.Selection.StreamSelectionSpan.GetText();
    MessageBox.Show(selectedText);
}

在其他任何地方,只需获取viewhost及其_view类型IWpfTextView

相关问题