嗨,我正在为visual studio做一个扩展,我需要的具体事情是获取编辑器窗口的选定文本以便进一步处理.有人知道有什么接口或服务吗?以前我需要找到开放解决方案的路径,为此我要求实现IVsSolution的服务,所以对于这个其他问题,我必须有一些服务为我提供这些信息.
Cra*_*rks 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;
}
Run Code Online (Sandbox Code Playgroud)
这是MSDN的IWpfTextViewHost,ITextDocument和ITextSelection的文档.
在 内部OnlayoutChanged,以下代码将弹出一条消息,其中包含所选代码:
if (_view.Selection.IsEmpty) return;
else
{
string selectedText = _view.Selection.StreamSelectionSpan.GetText();
MessageBox.Show(selectedText);
}
Run Code Online (Sandbox Code Playgroud)
在其他地方,只需获取 viewhost 及其_view类型IWpfTextView