Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In my VS extension, how can I programmatically preview a file in Visual Studio 2015/2017?

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

like image 333
Martin Lottering Avatar asked Aug 15 '17 09:08

Martin Lottering


People also ask

How do I see all codes in Visual Studio?

VS Code allows you to quickly search over all files in the currently opened folder. Press Ctrl+Shift+F and enter your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location.

How do I enable extensions in Visual Studio?

To open the Manage Extensions dialog, choose Extensions > Manage Extensions. Or, type Extensions in the search box and choose Manage Extensions. The pane on the left categorizes extensions by those that are installed, those available on Visual Studio Marketplace (Online), and those that have updates available.

How do I install an extension file in Visual Studio?

Install the Extension Unpack file from the downloaded . zip archive and run the CollaboratorVSExtension. vsix package. In the VSIX Installer, choose the desired Visual Studio version and click Install.


1 Answers

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.

like image 115
David Oliver Avatar answered Nov 16 '22 04:11

David Oliver