首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从EnvDTE.Window中获取ITextBuffer?

如何从EnvDTE.Window中获取ITextBuffer?
EN

Stack Overflow用户
提问于 2011-08-25 11:33:40
回答 1查看 2.6K关注 0票数 10

我有一个使用新的VS扩展API的托管语法高亮笔,它给了我一个ITextBuffer,这很棒。

在我的扩展的另一部分中,我获取了一个DTE对象,并将其附加到活动窗口更改事件,这给了我一个EnvDTE.Window对象。

代码语言:javascript
复制
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从窗口中拿出来。有人能告诉我一种直接的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-11 01:30:19

我使用的解决方案是获取Windows路径,然后将其与IVsEditorAdaptersFactoryServiceVsShellUtilities结合使用。

代码语言:javascript
复制
var openWindowPath = Path.Combine(window.Document.Path, window.Document.Name);
var buffer = GetBufferAt(openWindowPath);

代码语言:javascript
复制
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;
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7184857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档