How to be notified when a solution has been loaded for a VSPackage?

空扰寡人 提交于 2021-02-08 05:34:10

问题


I would like to be notified when a solution has been completely loaded. Inspired by this answer I tried implementing IVsSolutionEvents.

When I load a solution with two C# projects, wait until loading has finished and finally close Visual Studio 2017, the output shows only the following trace messages:

VSTestPackage1: OnAfterOpenProject
VSTestPackage1: OnQueryCloseSolution
VSTestPackage1: OnQueryCloseProject
VSTestPackage1: OnQueryCloseProject
VSTestPackage1: OnBeforeCloseSolution
VSTestPackage1: OnQueryCloseProject
VSTestPackage1: OnBeforeCloseProject
VSTestPackage1: OnQueryCloseProject
VSTestPackage1: OnBeforeCloseProject
VSTestPackage1: OnAfterCloseSolution

Is this the expected behavior? Why is OnAfterOpenSolution not being invoked?

This is the package implementation:

[PackageRegistration(UseManagedResourcesOnly = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[Guid(PackageGuidString)]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly",
    Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
[ProvideAutoLoad(VSConstants.UICONTEXT.SolutionHasMultipleProjects_string)]
public sealed class VSPackage1 : Package, IVsSolutionEvents
{
    public const string PackageGuidString = "2e655097-9510-4cf8-b9d4-ceeacebbaf3c";

    private DTE _dte;
    private uint _hSolutionEvents = uint.MaxValue;
    private IVsSolution _solution;

    /// <summary>
    ///     Initialization of the package; this method is called right after the package is sited, so this is the place
    ///     where you can put all the initialization code that rely on services provided by VisualStudio.
    /// </summary>
    protected override void Initialize()
    {
        base.Initialize();

        _dte = (DTE) GetService(typeof(DTE));

        AdviseSolutionEvents();
    }

    protected override void Dispose(bool disposing)
    {
        UnadviseSolutionEvents();

        base.Dispose(disposing);
    }

    private void AdviseSolutionEvents()
    {
        UnadviseSolutionEvents();

        _solution = GetService(typeof(SVsSolution)) as IVsSolution;

        _solution?.AdviseSolutionEvents(this, out _hSolutionEvents);
    }

    private void UnadviseSolutionEvents()
    {
        if (_solution == null) return;
        if (_hSolutionEvents != uint.MaxValue)
        {
            _solution.UnadviseSolutionEvents(_hSolutionEvents);
            _hSolutionEvents = uint.MaxValue;
        }

        _solution = null;
    }

    #region Implementation of IVsSolutionEvents

    int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
    {
        Trace.WriteLine("OnAfterOpenProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
    {
        Trace.WriteLine("OnQueryCloseProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
    {
        Trace.WriteLine("OnBeforeCloseProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
    {
        Trace.WriteLine("OnAfterLoadProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
    {
        Trace.WriteLine("OnQueryUnloadProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
    {
        Trace.WriteLine("OnBeforeUnloadProject", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
    {
        Trace.WriteLine("OnAfterOpenSolution", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
    {
        Trace.WriteLine("OnQueryCloseSolution", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnBeforeCloseSolution(object pUnkReserved)
    {
        Trace.WriteLine("OnBeforeCloseSolution", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    int IVsSolutionEvents.OnAfterCloseSolution(object pUnkReserved)
    {
        Trace.WriteLine("OnAfterCloseSolution", "VSTestPackage1");
        return VSConstants.S_OK;
    }

    #endregion
}

回答1:


Yes, this by design. The reason for the observed behavior, is because the event in question is firing before your package is loaded. You can readily test by observing that the event does fire, when you close the solution, and then reopen it (after your package is loaded). On the 2nd go around, you'll see the event fire.

Your example is using the SolutionHasMultipleProjects context guid, which ensures your package will only load if a solution has multiple projects. The only way for the IDE to determine that, would be to first have the solution load, and then set the UI context. So basically, you're setting up the event handler just a little too late.

If you want to ensure you receive that particular notification, you can register your package to load with NoSolution_string and SolutionExists_string. But that's somewhat evil, as this forces your package to always load (even when it isn't needed), which is a less that desirable solution.

Using SolutionExistsAndFullyLoadedContext might be a better way to go. When your package is initially loaded, you'll know that condition has been met, and you can run your handler code just before returning from your package's Initialize override. And your original IVsSolutionEvents handler will be invoked on subsequent solution loads.

You might also want to consider registering/using a rule-based UI context as described below:

How to: Use Rule-based UI Context for Visual Studio Extensions

Sincerely, Ed Dore




回答2:


I know the answer, but I DON"t KNOW how to put class code in this

Add a async package call VSPackageEvents, and put this code in file, and and replace dte with your package dte

using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using Task = System.Threading.Tasks.Task;

namespace VSIXProject
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the
    /// IVsPackage interface and uses the registration attributes defined in the framework to
    /// register itself and its components with the shell. These attributes tell the pkgdef creation
    /// utility what data to put into .pkgdef file.
    /// </para>
    /// <para>
    /// To get loaded into VS, the package must be referred by &lt;Asset Type="Microsoft.VisualStudio.VsPackage" ...&gt; in .vsixmanifest file.
    /// </para>
    /// </remarks>
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [InstalledProductRegistration("#1110", "#1112", "1.0", IconResourceID = 1400)] // Info on this package for Help/About
    [Guid(VSPackageEvents.PackageGuidString)]
    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
#pragma warning disable VSSDK004 // Use BackgroundLoad flag in ProvideAutoLoad attribute for asynchronous auto load.
    [ProvideAutoLoad(UIContextGuids80.SolutionExists)]
#pragma warning restore VSSDK004 // Use BackgroundLoad flag in ProvideAutoLoad attribute for asynchronous auto load.
    public sealed class VSPackageEvents : AsyncPackage
    {
        EnvDTE.DTE dte = null;
        EnvDTE.Events events = null;
        EnvDTE.SolutionEvents solutionEvents = null;
        /// <summary>
        /// VSPackageEvents GUID string. Replace this Guid
        /// </summary>
        public const string PackageGuidString = "12135331-70d8-48bb-abc7-5e5ffc65e041";

        /// <summary>
        /// Initializes a new instance of the <see cref="VSPackageEvents"/> class.
        /// </summary>
        public VSPackageEvents()
        {
            // Inside this method you can place any initialization code that does not require
            // any Visual Studio service because at this point the package object is created but
            // not sited yet inside Visual Studio environment. The place to do all the other
            // initialization is the Initialize method.
        }
        private void SolutionEvents_Opened()
        {
// put your code here after opened event
        }
        private void SolutionEvents_AfterClosing()
        {
// put your code here after closed event
        }

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
        /// <param name="progress">A provider for progress updates.</param>
        /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            // When initialized asynchronously, the current thread may be a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
            // replace dte from next line with your dte package
            // dte = Utilities.Utility.GetEnvDTE(this);
            events = dte.Events;       
            solutionEvents = events.SolutionEvents;
            solutionEvents.Opened += SolutionEvents_Opened;
            solutionEvents.AfterClosing += SolutionEvents_AfterClosing;
        }    

    }
}


来源:https://stackoverflow.com/questions/44108369/how-to-be-notified-when-a-solution-has-been-loaded-for-a-vspackage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!