0

I'm trying to set a macro command to collapse all methods when file is open. is there any way to run this macro when file is open? is there a better solution to collapse all code when file is open? i'm using visual studio 2019

Amit Levi
  • 1
  • 1

1 Answers1

0

You can run a macro when opening a file with my Visual Commander extension.

I've converted old VB code from this answer to a C# Visual Commander extension:

public class E : VisualCommanderExt.IExtension
{
    public void SetSite(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        this.DTE = DTE;
        events = DTE.Events;
        windowEvents = events.WindowEvents;
        windowEvents.WindowActivated += OnWindowActivated;

        documentEvents = events.DocumentEvents;
        documentEvents.DocumentOpened += OnDocumentOpened;
    }

    public void Close()
    {
        windowEvents.WindowActivated -= OnWindowActivated;
        documentEvents.DocumentOpened -= OnDocumentOpened;
    }

    private void OnDocumentOpened(EnvDTE.Document Document)
    {
        try
        {
            documentOpened = true;
        }
        catch (System.Exception)
        {
        }
    }

    private void OnWindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
    {
        try
        {
            if (documentOpened)
                DTE.ExecuteCommand("Edit.CollapsetoDefinitions");
            documentOpened = false;
        }
        catch (System.Exception)
        {
        }
    }

    private EnvDTE80.DTE2 DTE;
    private EnvDTE.Events events;
    private EnvDTE.WindowEvents windowEvents;
    private EnvDTE.DocumentEvents documentEvents;
    private bool documentOpened;
}

But it doesn't (always) work. Probably needs a delay to override VS restoring remembered outlining for the file.

Sergey Vlasov
  • 26,641
  • 3
  • 64
  • 66