10

我有一个使用新的 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 中取出。谁能告诉我一个直接的方法来做到这一点?

4

1 回答 1

12

我使用的解决方案是获取 Windows 路径,然后将其与IVsEditorAdaptersFactoryServiceand结合使用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;
}
于 2011-09-10T17:30:18.670 回答