Logo
HOWTO: Canceling a build from a Visual Studio .NET add-in.

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio .NET 2002
Date: October 2005   Microsoft Visual Studio .NET 2003
Updated: March 2013   Microsoft Visual Studio 2005
      Microsoft Visual Studio 2008
      Microsoft Visual Studio 2010
      Microsoft Visual Studio 2012
Introduction

This article describes how to cancel a build from a Visual Studio .NET add-in if some condition is not met.

More Information

Sometimes you may want to use an add-in or macro to perform some action before a solution or project is built, and to cancel the build action if some condition is not met. For this purpose typically you use the events OnBuildBegin or OnBuildProjConfigBegin of the EnvDTE.BuildEvents class. However, those events lack a boolean output "cancel" parameter to cancel the build. To cancel the build in such scenario, you can execute the "Build.Cancel" command of Visual Studio .NET.
 
The following VB.NET add-in code shows how to cancel a build:

Private m_objDTE As EnvDTE.DTE
Private WithEvents m_objBuildEvents As EnvDTE.BuildEvents
 
Public Sub OnConnection(ByVal application As Object, _
   ByVal connectMode As Extensibility.ext_ConnectMode, _
   ByVal addInInst As Object, ByRef custom As System.Array) _
   Implements Extensibility.IDTExtensibility2.OnConnection
 
   m_objDTE = CType(application, EnvDTE.DTE)
   m_objBuildEvents = m_objDTE.Events.BuildEvents
 
End Sub
 
Private Sub m_objBuildEvents_OnBuildBegin(ByVal Scope As EnvDTE.vsBuildScope, _
   ByVal Action As EnvDTE.vsBuildAction) _
   Handles m_objBuildEvents.OnBuildBegin
 
   Select Case Action

      Case vsBuildAction.vsBuildActionBuild, vsBuildAction.vsBuildActionRebuildAll

         If MessageBox.Show("Do you want to cancel the build?", "Question", _
            MessageBoxButtons.YesNo) = DialogResult.Yes Then

            m_objDTE.ExecuteCommand("Build.Cancel")

         End If

   End Select
End Sub



Go to the 'Visual Studio Extensibility (VSX)' web site for more articles like this (Articles section)


Top