I have a managed syntax highlighter using the new VS extensibility API's and it gives me an ITextBuffer, which is great.
In another part of my extension I am getting a DTE object and attaching to the active window changed event, which gives me an EnvDTE.Window object.
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
}
I would like to get the ITextBuffer out of Window in this method. Can anyone tell me a straight forward way to do that?
The solution I used was to get the Windows path then use it in conjuction with IVsEditorAdaptersFactoryService and VsShellUtilities.
var openWindowPath = Path.Combine(window.Document.Path, window.Document.Name);
var buffer = GetBufferAt(openWindowPath);
and
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With