2 minute read

I had spent considerable time trying to open a new document window and then set the document text to the result of the generated template text. I found this to be an almost impossible task and proposed this on the Microsoft Visual Studio Extensibility forums. The response that I got was that after looking into this functionality the best approach would be to save the text to a file and then open the document window.

I looked into this, I think trying to open one of the built in editors, in a normal editor tab populated with data that does not exist on disk is going to be a pointless battle, the system is set up to deal with files, generally from disk.

I don’t see any good (read easy or even logical) way to open an ‘empty’ editor that is fed data from memory. There is likely a way to do this, the folks on the editor forum may have suggestions, but I don’t see any clear path to it and if you find it I foresee you having to fight a lot of battles as you are trying to do something far from the ‘mainstream’.

I looked into the File -> New File scenario since it is similar but even that uses a temporary file on disk. Saving the content you want to display to disk in the users temp directory and opening that file would probably be 500% easier than trying to do what you want to do above

One to One could more than likely use EnvDTE.get_IsOpenFile() or EnvDTE.OpenFile() to accomplish this task, but I choose the following method to open a new Document Window. One first must check to see if the document is already open and if it isn’t make the call to open it. We return the IVsWindowFrame from this method, as it allows one to do additional operations on this opened document. Note that the ServiceFactory.ServiceProvider returns an instance of EnvDTE.DTE.

public static IVsWindowFrame OpenDocumentInNewWindow(string filePath) {
  if(String.IsNullOrEmpty(filePath) || !File.Exists(filePath))
    return null;

  IVsUIHierarchy hierarchy;
  uint itemId;
  IVsWindowFrame frame = null;
  if (!VsShellUtilities.IsDocumentOpen(ServiceFactory.ServiceProvider, filePath,
      VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame))
  {
    VsShellUtilities.OpenDocument(ServiceFactory.ServiceProvider, filePath,
      VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame);
  }

  if (frame != null)
    frame.Show();

  return frame;
}

Join the mailing list

Get notified of new posts and related content to your inbox. I will never sell you anything and I will NEVER sell your email address.