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

嗨我正在为visual studio做一个扩展,我需要的具体事情是获取编辑器窗口的选定文本以便进一步处理。 有人知道这个界面或服务有哪些? 以前我需要找到开放解决方案的路径,为此我要求一个实现IVsSolution的服务,所以对于这个其他问题,我必须有一些服务为我提供这些信息。

为了澄清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的IWpfTextViewHost , ITextDocument和ITextSelection的文档。

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

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

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