我有一个使用新的 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 中取出。谁能告诉我一个直接的方法来做到这一点?
最佳答案
我使用的解决方案是获取 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;
}
关于c# - 如何从 EnvDTE.Window 中获取 ITextBuffer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7184857/