您好,我正在为 visual studio 做一个扩展,我需要做的具体事情是获取编辑器窗口的选定文本以进行进一步处理。有人知道这个有什么接口(interface)或服务吗? 以前我需要找到开放解决方案的路径,为此我要求一个实现 IVsSolution 的服务,所以对于这个其他问题,我认为必须有一些服务可以为我提供这些信息。
最佳答案
为了阐明 Stacker 的回答中的“只获取 View 主机”,这里是完整代码,说明如何从 Visual Studio 2010 VSPackage 中的其他任何位置获取当前编辑器 View 以及 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;
}
这是 IWpfTextViewHost 的 MSDN 文档, ITextDocument , 和 ITextSelection .
关于c# - 获取编辑器窗口的选定文本..visual studio 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2868127/