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

1

11

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

Wiry answered 15/8, 2017 at 9:10 Comment(4)
Visual Studio already has a single-click previewTitanesque
@MickyD, thanks. I edited the question to point out that I want to do it in code in my VS extension. I cannot find where the Visual Studio SDK provides that feature to extensions.Wiry
do you want to get preview window via programmatically?Organic
@ColeWu-MSFT Yes, Thanks I updated the question. Sorry for the confusion.Wiry
Z
2

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.

Zulmazulu answered 30/8, 2020 at 9:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.