Compartir a través de


Cómo: Utilizar los objetos BuildManager y BuildManagerEvents

Actualización: noviembre 2007

El objeto BuildManager se utiliza para administrar y mostrar los archivos ejecutables portables (PE) creados por las herramientas personalizadas (generadores de un solo archivo), que generan resultados en tiempo de diseño. Cuando se cambian o se eliminan elementos del proyecto que generan archivos ejecutables portables temporales, se producen eventos BuildManagerEvents.

La información siguiente detalla cómo programar en los objetos BuildManager y BuildManagerEvents de un complemento de Visual Studio.

Nota:

Los cuadros de diálogo y comandos de menú que se ven pueden diferir de los descritos en la Ayuda, en función de los valores de configuración o de edición activos. Estos procedimientos se desarrollaron con la Configuración general de desarrollo activa. Para cambiar la configuración, elija la opción Importar y exportar configuraciones del menú Herramientas. Para obtener más información, vea Valores de configuración de Visual Studio.

Para utilizar los objetos BuildManager y BuildManagerEvents

  1. Cree un proyecto de complemento de Visual Studio mediante Visual C#.

  2. En el menú Proyecto, haga clic en Agregar referencia, en la ficha .NET, seleccione System.Windows.Forms, VSLangProj, VSLangProj2 y VSLangProj80 y, a continuación, haga clic en Aceptar.

  3. Agregue las instrucciones siguientes al principio del archivo Connect.cs.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    using System.Windows.Forms;
    
  4. Agregue la declaración siguiente al final de la clase Connect para declarar el controlador BuildManagerEvents.

    private DTE2 _applicationObject;
    private AddIn _addInInstance;
    private VSLangProj.BuildManagerEvents buildMgrEvents;
    
  5. Agregue la llamada de método siguiente al método OnConnection.

    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    // Call the BuildMangerSample method.
    BuildManagerSample(_applicationObject);
    
  6. Agregue la declaración de método BuildManagerSample directamente debajo del método OnConnection.

    public void BuildManagerSample(DTE2 dte)
    {
    }
    
  7. Agregue las declaraciones siguientes al principio del método BuildManagerSample.

    Solution2 soln = (Solution2)_applicationObject.Solution;
    Project proj;
    VSProject2 vsproj;
    BuildManager bldMgr;
    
  8. Agregue el código siguiente al método BuildManagerSample para convertir el proyecto en un objeto VSProject2.

    proj = soln.Projects.Item(1);
    // Get a reference to the VSProject2 object.
    vsproj = (VSProject2)proj.Object;
    
  9. Agregue el código para mostrar los monikers del archivo PE en un cuadro de mensaje a través de BuildDesignTimeOutput.

    bldMgr = vsproj.BuildManager;
    Array monikers = null;
    String msg = null;
    Object obj = bldMgr.DesignTimeOutputMonikers;
    if (obj != null)
    {
        try
        {
            monikers = (System.Array)obj;
            foreach(String tempmoniker in monikers)
                {
                    msg += bldMgr.BuildDesignTimeOutput(tempmoniker) 
    + "\n";
                }
            }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    MessageBox.Show("The build design-time output is:" + "\n"  
    + msg, "Temporary PE Monikers");
    }
    
  10. Agregue el código siguiente al método BuildManagerSample para crear los controladores de eventos BuildManagerEvents.

    //Hook up buildmanager events.
    buildMgrEvents = vsproj.Events.BuildManagerEvents;
    buildMgrEvents.DesignTimeOutputDeleted +=
    new _dispBuildManagerEvents_DesignTimeOutputDeletedEventHandler
    (buildMgrEvents_DesignTimeOutputDeleted);
    buildMgrEvents. DesignTimeOutputDirty +=
    new _dispBuildManagerEvents_DesignTimeOutputDirtyEventHandler(
    buildMgrEvents_DesignTimeOutputDirty);
    
  11. . Agregue procedimientos para cada evento relacionado con el objeto BuildManagerEvents.

    void buildMgrEvents_DesignTimeOutputDirty
    (string bstrOutputMoniker)
    {
        MessageBox.Show(bstrOutputMoniker + " is dirty."
    , "BuildManager Events");
    }
    
    void buildMgrEvents_DesignTimeOutputDeleted
    (string bstrOutputMoniker)
    {
        MessageBox.Show(bstrOutputMoniker + " was deleted."
    , "BuildManager Events");
    }
    
  12. Finalmente, agregue el código siguiente al método OnDisconnection para deshabilitar el control de eventos.

    public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
    {
        // If the delegate handlers have been connected, then 
        // disconnect them here. 
        // If you do not do this, the handlers may still 
        // fire because garbage collection has not removed them.
        if (buildMgrEvents != null)
        {
            buildMgrEvents.DesignTimeOutputDeleted -= new _dispBuildManagerEvents_DesignTimeOutputDeletedEventHandler(buildMgrEvents_DesignTimeOutputDeleted);        buildMgrEvents.DesignTimeOutputDirty -= new _dispBuildManagerEvents_DesignTimeOutputDirtyEventHandler(buildMgrEvents_DesignTimeOutputDirty);
        }
    }
    

    El código completo aparece en la sección Ejemplo de este tema.

  13. Para generar el complemento, haga clic en la opción Generar solución del menú Generar.

  14. Abra un proyecto de Visual C#, Visual J# o Visual Basic en el entorno de desarrollo integrado (IDE) de Visual Studio.

  15. Para agregar un conjunto de datos al proyecto, haga clic en la opción Agregar nuevo elemento del menú Proyecto. Seleccione DataSet en el cuadro de diálogo Agregar nuevo elemento y haga clic en Aceptar.

    Un archivo DataSet garantiza que el proyecto tiene una herramienta personalizada (generador de un único archivo) asociada a él.

En el menú Herramientas, haga clic en Administrador de complementos y seleccione el complemento del cuadro de diálogo Administrador de complementos. Haga clic en Aceptar para ejecutar el complemento.

Para probar el código BuildManagerEvents

  • Para ver la activación del controlador BuildManagerEvents, agregue un nuevo conjunto de datos al proyecto, modifique las propiedades del archivo del conjunto de datos o elimine el archivo del conjunto de datos.

    Para modificar las propiedades del archivo del conjunto de datos:

    1. Seleccione el archivo del conjunto de datos en el Explorador de soluciones.

    2. Haga clic con el botón secundario del mouse (ratón) en el archivo y seleccione Propiedades en el menú desplegable.

    3. En la ventana Propiedades, modifique cualquiera de los campos.

    Para eliminar el conjunto de datos:

    1. Seleccione el archivo del conjunto de datos en el Explorador de soluciones.

    2. Haga clic con el botón secundario del mouse en el archivo y seleccione Eliminar en el menú desplegable.

Ejemplo

El ejemplo siguiente es un complemento básico de Visual Studio que muestra cómo utilizar los objetos BuildManager y BuildManagerEvents utilizando la automatización de Visual Studio.

using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using VSLangProj;
using VSLangProj2;
using VSLangProj80;
using System.Windows.Forms;
namespace MyAddIn
{
public class Connect : Object, IDTExtensibility2
    {
        public Connect()
        {
        }
        public void OnConnection(object application, 
ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            _applicationObject = (DTE2)application;
            _addInInstance = (AddIn)addInInst;
            // Call the BuildMangerSample method.
            BuildManagerSample(_applicationObject);
        }
        public void BuildManagerSample(DTE2 dte)
        {
            try
            {
                Solution2 soln =
 (Solution2)_applicationObject.Solution;
                Project proj;
                VSProject2 vsproj;
                BuildManager bldMgr;
                proj = soln.Projects.Item(1);
                // Cast to the VSProject2 object.
                vsproj = (VSProject2)proj.Object;
                bldMgr = vsproj.BuildManager;
                Array monikers = null;
                String msg = null;
                Object obj = bldMgr.DesignTimeOutputMonikers;
                if (obj != null)
                {
                    try
                    {
                        monikers = (System.Array)obj;
                        foreach(String tempmoniker in monikers)
                        {
                            msg +=
 bldMgr.BuildDesignTimeOutput(tempmoniker) + "\n";
                        }
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    MessageBox.Show("The build design-time output is:"
+ "\n"  + msg, "Temporary PE Monikers");
                }
                //Hook up buildmanager events.
                buildMgrEvents = vsproj.Events.BuildManagerEvents;
                buildMgrEvents.DesignTimeOutputDeleted +=new
 _dispBuildManagerEvents_DesignTimeOutputDeletedEventHandler
(buildMgrEvents_DesignTimeOutputDeleted);
                buildMgrEvents.DesignTimeOutputDirty +=new
 _dispBuildManagerEvents_DesignTimeOutputDirtyEventHandler
(buildMgrEvents_DesignTimeOutputDirty);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void buildMgrEvents_DesignTimeOutputDirty
(string bstrOutputMoniker)
        {
            MessageBox.Show(bstrOutputMoniker + " is dirty.", 
"BuildManager Events");
        }
        void buildMgrEvents_DesignTimeOutputDeleted(
string bstrOutputMoniker)
        {
            MessageBox.Show(bstrOutputMoniker + " was deleted."
, "BuildManager Events");
        }
        public void OnDisconnection(ext_DisconnectMode disconnectMode
, ref Array custom)
        {
            // If the delegate handlers have been connected, then 
            // disconnect them here. 
            // If you do not do this, the handlers may still 
            // fire because garbage collection has not removed them.
            if (buildMgrEvents != null)
            {
                buildMgrEvents.DesignTimeOutputDeleted -= new
 _dispBuildManagerEvents_DesignTimeOutputDeletedEventHandler
(buildMgrEvents_DesignTimeOutputDeleted);
                buildMgrEvents.DesignTimeOutputDirty -= new
 _dispBuildManagerEvents_DesignTimeOutputDirtyEventHandler
(buildMgrEvents_DesignTimeOutputDirty);
            }
        }
        public void OnAddInsUpdate(ref Array custom)
        {
        }
        public void OnStartupComplete(ref Array custom)
        {
        }
        public void OnBeginShutdown(ref Array custom)
        {
        }
        private DTE2 _applicationObject;
        private AddIn _addInInstance;
        private VSLangProj.BuildManagerEvents buildMgrEvents;
    }
}
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports EnvDTE80
Imports VSLangProj
Imports VSLangProj2
Imports VSLangProj80

Public Class Connect
    Implements IDTExtensibility2
    Dim _applicationObject As DTE2
    Dim _addInInstance As AddIn
    Public WithEvents buildMgrEvents As VSLangProj.BuildManagerEvents
    Public Sub New()
    End Sub
    Public Sub OnConnection(ByVal application As Object, ByVal _
    connectMode As ext_ConnectMode, ByVal addInInst As Object, _
    ByRef custom As Array) Implements IDTExtensibility2.OnConnection
        _applicationObject = CType(application, DTE2)
        _addInInstance = CType(addInInst, AddIn)
        BuildManagerSample(_applicationObject)
    End Sub
    Sub BuildManagerSample(ByVal dte As DTE2)
        Try
            Dim soln As Solution2 = CType(_applicationObject.Solution _
            , Solution2)
            Dim proj As Project
            Dim vsproj As VSProject2
            Dim bldMgr As BuildManager
            proj = soln.Projects.Item(1)
            ' Cast the project to a VSProject2.
            vsproj = CType(proj.Object, VSProject2)
            bldMgr = vsproj.BuildManager
            Dim monikers As String() = Nothing
            Dim moniker As String = Nothing
            Dim msg As String = ""
            Dim obj As Object = bldMgr.DesignTimeOutputMonikers
            If Not obj Is Nothing Then
                Try
                    monikers = CType(obj, String())
                    For Each moniker In monikers
                        msg &= bldMgr.BuildDesignTimeOutput(moniker)  _
                        + vbCr
                    Next
                Catch ex As System.Exception
                    MsgBox(ex.ToString)
                End Try
                MsgBox("The build design-time output is:" + vbCr  _
                + msg, MsgBoxStyle.Information _
                , "BuildManager Monikers")
            End If
            buildMgrEvents = vsproj.Events.BuildManagerEvents
            AddHandler buildMgrEvents.DesignTimeOutputDeleted _
            , AddressOf OutputDeleted
            AddHandler buildMgrEvents.DesignTimeOutputDirty _
            , AddressOf OutputDirty
        Catch ex As System.Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
    Sub OutputDeleted(ByVal deletedMoniker As String)
        MsgBox(deletedMoniker & " was deleted." _
        , MsgBoxStyle.Information, "BuildManagerEvents Information")
    End Sub
    Sub OutputDirty(ByVal dirtyMoniker As String)
        MsgBox(dirtyMoniker & " is dirty." _
        , MsgBoxStyle.Information, "BuildManagerEvents Information")
    End Sub
    Public Sub OnDisconnection(ByVal disconnectMode  _
    As ext_DisconnectMode, ByRef custom As Array)  _
    Implements IDTExtensibility2.OnDisconnection
        ' Turns off BuildManager event handling when the 
        ' add-in shuts down.
        buildMgrEvents = Nothing
    End Sub
    Public Sub OnAddInsUpdate(ByRef custom As Array)  _
    Implements IDTExtensibility2.OnAddInsUpdate
    End Sub
    Public Sub OnStartupComplete(ByRef custom As Array)  _
    Implements IDTExtensibility2.OnStartupComplete
    End Sub
    Public Sub OnBeginShutdown(ByRef custom As Array)  _
    Implements IDTExtensibility2.OnBeginShutdown
    End Sub
End Class

Compilar el código

Para compilar este código, cree un nuevo proyecto de complemento de Visual Studio y reemplace el código de la clase Connect por el código del ejemplo. Antes de ejecutar el complemento, abra un proyecto de Visual C#, Visual Basic o Visual J# en el IDE de Visual Studio. Para obtener información sobre cómo ejecutar un complemento, vea Cómo: Controlar complementos con el Administrador de complementos.

Vea también

Conceptos

Introducción al objeto BuildManager

Introducción a la extensibilidad de proyectos

Otros recursos

Automatización y extensibilidad en Visual Studio