获取编辑器窗口中选定的文本..Visual Studio扩展程序

8

你好,我正在为Visual Studio制作一个扩展程序,需要获取编辑器窗口中选定的文本以进行进一步处理。有人知道哪个接口或服务可以提供此功能吗? 之前,我需要定位打开解决方案的路径,因此我寻求实现IVsSolution的服务。对于这个问题,我认为必须有某个服务可以提供这些信息。

2个回答

12

为了澄清Stacker的答案中的“just get the viewhost”,以下是获取当前编辑器视图的完整代码,以及从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提供的对于 IWpfTextViewHost, ITextDocumentITextSelection 的文档。


现在,您可能需要使用 ServiceProvider.GetServiceAsync 将其转换为异步函数。实际上,上面提到的 URL 也已更新为使用它。 - General Grievance

3

OnlayoutChanged 中,以下代码将弹出一个带有所选代码的消息:

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

在其他任何地方,只需获取_viewhost及其类型为IWpfTextView_view即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接