c# - 如何从 EnvDTE.Window 中获取 ITextBuffer?

标签 c# visual-studio-2010 envdte

我有一个使用新的 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 路径,然后将其与 IVsEditorAdaptersFactoryServiceVsShellUtilities 结合使用。

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/

相关文章:

c++ - 日志(PCTSTR 格式,...)和日志(PCTSTR 文本): error C2668 ambiguous call to overloaded function

c - 在 Visual Studio 2010 中从 dll 崩溃中释放主程序内存

visual-studio - 以编程方式导入/导出 VS 设置?

visual-studio-2012 - 为什么 Visual Studio 后台线程如此慢?

c# - 如何通过网络服务流式传输文档?

c# - 应该在编码中使用什么加密以及它如何影响 key 和初始化向量?

c# - TinyMCE 包

c# - 在 OOP 方法重载中使用 float 会出现错误

c# - Visual Studio 2010 内存消耗

c# - 从 DTE (EnvDte) 获取进程 ID