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
}

このメソッドで Window から ITextBuffer を取得したいと思います。誰かがそれを行うための簡単な方法を教えてもらえますか?

4

1 に答える 1

12

私が使用した解決策は、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;
}
于 2011-09-10T17:30:18.670 に答える