10

In my Visual Studio extension I display related files.

I have code that can open a file in Visual Studio.

I want code that can preview a file

This is the code I use to open a file using the DTE2 object. But how can I preview the file?

public void ViewFile(FileInfo file)
{
    if (null == file)
        throw new ArgumentNullException(nameof(file));

    var dte2 = (EnvDTE80.DTE2)DTE;
    dte2.MainWindow.Activate();
    var newWindow = dte2.ItemOperations.IsFileOpen(file.FullName)
            ? FindWindow(file.FullName)
            : dte2.ItemOperations.OpenFile(file.FullName);
    newWindow.Activate();
}

This is a previewed file, if you single click it in Solution Explorer:

enter image description here

This is an opened file, if you double click it in Solution Explorer, or make a change to a previewed file:

enter image description here

Martin Lottering
  • 1,624
  • 19
  • 31

1 Answers1

1

You can open a document in the preview tab from a Visual Studio extension using NewDocumentStateScope:

    private void OpenDocumentInPreview(DTE dte, string filename)
    {
        using (new NewDocumentStateScope(__VSNEWDOCUMENTSTATE.NDS_Provisional, VSConstants.NewDocumentStateReason.SolutionExplorer))
        {
            dte.ItemOperations.OpenFile(filename);
        }
    }

As when a preview is initiated in other ways, if the file is already open in a normal tab, this code will switch to that tab rather than using the preview tab.

David Oliver
  • 2,251
  • 12
  • 12