你好,我正在为Visual Studio制作一个扩展程序,需要获取编辑器窗口中选定的文本以进行进一步处理。有人知道哪个接口或服务可以提供此功能吗? 之前,我需要定位打开解决方案的路径,因此我寻求实现IVsSolution的服务。对于这个问题,我认为必须有某个服务可以提供这些信息。
你好,我正在为Visual Studio制作一个扩展程序,需要获取编辑器窗口中选定的文本以进行进一步处理。有人知道哪个接口或服务可以提供此功能吗? 之前,我需要定位打开解决方案的路径,因此我寻求实现IVsSolution的服务。对于这个问题,我认为必须有某个服务可以提供这些信息。
为了澄清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, ITextDocument 和 ITextSelection 的文档。
OnlayoutChanged
中,以下代码将弹出一个带有所选代码的消息:
if (_view.Selection.IsEmpty) return;
else
{
string selectedText = _view.Selection.StreamSelectionSpan.GetText();
MessageBox.Show(selectedText);
}
在其他任何地方,只需获取_viewhost
及其类型为IWpfTextView
的_view
即可。
ServiceProvider.GetServiceAsync
将其转换为异步函数。实际上,上面提到的 URL 也已更新为使用它。 - General Grievance