我有一个使用新的VS扩展性API的托管语法高亮显示器,它给了我一个ITextBuffer
,这很棒。
在我的扩展程序的另一部分中,我获取了一个DTE对象并附加到活动窗口已更改事件,这会给我一个EnvDTE.Window
对象。
var dte = (EnvDTE.DTE)this.GetService(typeof(EnvDTE.DTE));
dte.Events.WindowEvents.WindowActivated += WindowEvents_WindowActivated;
// ...
private void WindowEvents_WindowActivated(EnvDTE.Window GotFocus, EnvDTE.Window LostFocus)
{
// ???
// Profit
}
我想在此方法中将ITextBuffer从Window中取出。谁能告诉我一个直截了当的方法呢?
答案 0 :(得分:10)
我使用的解决方案是获取Windows路径,然后将其与IVsEditorAdaptersFactoryService
和VsShellUtilities
结合使用。
var openWindowPath = Path.Combine(window.Document.Path, window.Document.Name);
var buffer = GetBufferAt(openWindowPath);
和
internal ITextBuffer GetBufferAt(string filePath)
{
var componentModel = (IComponentModel)GetService(typeof(SComponentModel));
var editorAdapterFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>();
var serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(MetaSharpPackage.OleServiceProvider);
IVsUIHierarchy uiHierarchy;
uint itemID;
IVsWindowFrame windowFrame;
if (VsShellUtilities.IsDocumentOpen(
serviceProvider,
filePath,
Guid.Empty,
out uiHierarchy,
out itemID,
out windowFrame))
{
IVsTextView view = VsShellUtilities.GetTextView(windowFrame);
IVsTextLines lines;
if (view.GetBuffer(out lines) == 0)
{
var buffer = lines as IVsTextBuffer;
if (buffer != null)
return editorAdapterFactoryService.GetDataBuffer(buffer);
}
}
return null;
}