Search code examples
c#visual-studio-extensionsvsixenvdte

Can I get my code to run directly after the Visual Studio "Clean Solution" command?


I'm creating my first Visual Studio extension and everything would just be perfect if I can get my code to run immediately after the Visual Studio "Clean Solution" command finishes execution.

I found EnvDTE._dispBuildEvents_Event.OnBuildDone, but can't seem to find it's cousin OnCleanDone.

Does an event like this exist at all? Or, is there a different approach I could take?

Thanks, giants!


Solution

  • Turns out Clean Solution is considered a BuildEvent and therefore fires EnvDTE._dispBuildEvents_Event.OnBuildDone.

    All you need to do, is to check if parameter Action == vsBuildAction.vsBuildActionClean.

    My full solution below (with two remarks):

    • I get the warning that "One or more extensions were loaded using deprecated APIs", so I have some work to do, and will update this code snippet once I have it fixed. Maybe the naming conventions and lack of Generics should have been an indication that I'm doing this in an out-of-fashion manner 👴

    • If I don't keep an active reference to DTE.Events.BuildEvents, OnBuildDone won't fire. I don't know why yet.

      public sealed class OnCleanSolutionDoneExtension : Package
      {
          protected override void Initialize()
          {
              base.Initialize();
      
              this.BuildEvents.OnBuildDone += OnBuildDone;
          }
      
          void OnBuildDone(vsBuildScope scope, vsBuildAction action)
          {
              if (action == vsBuildAction.vsBuildActionClean)
              {
                  // 💰
              }
          }
      
          private BuildEvents BuildEvents
          {
              get
              {
                  if (this.buildEvents == null)
                  {
                      this.buildEvents = this.DevelopmentToolsEnvironment.Events.BuildEvents;
                  }
      
                  return this.buildEvents;
              }
          }
      
          private BuildEvents buildEvents;
      
          private DTE DevelopmentToolsEnvironment
          {
              get
              {
                  return this.GetService(typeof(DTE)) as DTE;
              }
          }
      
          protected override void Dispose(bool disposing)
          {
              try
              {
                  if (disposing)
                  {
                      this.buildEvents.OnBuildDone -= OnBuildDone;
      
                      GC.SuppressFinalize(this);
                  }
              }
              finally
              {
                  base.Dispose(disposing);
              }
          }
      }