Logo
HOWTO: Create a CommandBarButton without a command from a Visual Studio .NET add-in

Author: Carlos J. Quintero (Microsoft MVP) Applies to: Microsoft Visual Studio .NET 2002
Date: August 2011   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 explains how to create buttons (CommandBarButton) on a commandbar without an associated command.

More Information

As explained in the article HOWTO: Adding buttons, commandbars and toolbars to Visual Studio .NET from an add-in, all buttons (CommandBarButton) on commandbars (toolbars, menus, etc.) should be created from a command (EnvDTE.Command). The reasons are the following:

  • Users can associate a keyboard binding to the command.
  • Users can customize the user interface of Visual Studio ("Tools", "Customize..." window) adding buttons from commands to the desired toolbar, menu, context menu, etc.
  • Commands can be executed using the Command window.
  • Commands can be executed programatically (from a macro or add-in, using the DTE.ExecuteCommand method).

Nonetheless, Visual Studio allows to create CommandBarButtons without a command, using the CommandBar.Controls.Add method.

The add-in sample below creates a button at the end of the "Standard" commandbar without using a command when loaded, and it removes it when unloaded. Notice that in this sample it creates it without an image. To add an image you should use the CommandBarButton.Picture and CommandBarButton.Mask properties, which is somewhat complicated because they are of the type Stdole.IPictureDisp (see the article HOWTO: Creating custom pictures for Visual Studio .NET add-ins commands, buttons and toolwindows).

Language: C#   Copy Code Copy Code (IE only)
using System;
using Extensibility;
using Microsoft.VisualStudio.CommandBars;
using EnvDTE;
using System.Windows.Forms;

namespace MyAddin
{
   public class Connect: IDTExtensibility2
   {
      // Variables for IDE and add-in instances
      private EnvDTE.DTE applicationObject;
      private EnvDTE.AddIn addInInstance;

      // Buttons that will be created on built-in commandbars of Visual Studio
      // We must keep them at class level to remove them when the add-in is unloaded
      private CommandBarButton myStandardCommandBarButton;

      public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
      {
         try
         {
            applicationObject = (EnvDTE.DTE)application;
            addInInstance = (EnvDTE.AddIn)addInInst;

            switch (connectMode)
            {
               case ext_ConnectMode.ext_cm_UISetup:

                  // Do nothing for this add-in with temporary user interface
                  break;

               case ext_ConnectMode.ext_cm_Startup:

                  // The add-in was marked to load on startup
                  // Do nothing at this point because the IDE may not be fully initialized
                  // Visual Studio will call OnStartupComplete when fully initialized
                  break;

               case ext_ConnectMode.ext_cm_AfterStartup:

                  // The add-in was loaded by hand after startup using the Add-In Manager
                  // Initialize it in the same way that when is loaded on startup
                  AddTemporaryUI();
                  break;
            }
         }
         catch (System.Exception e)
         {
            System.Windows.Forms.MessageBox.Show(e.ToString());
         }
      }

      public void OnStartupComplete(ref System.Array custom)
      {
         AddTemporaryUI();
      }

      private void AddTemporaryUI()
      {
         CommandBar standardCommandBar;
         CommandBars commandBars;

         try
         {
            commandBars = (CommandBars)applicationObject.CommandBars;

            // Get the "Standard" toolbar
            standardCommandBar = commandBars["Standard"];

            // Add a button to the built-in "Standard" toolbar
            myStandardCommandBarButton = (CommandBarButton)standardCommandBar.Controls.Add(
                 MsoControlType.msoControlButton, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);

            // Change some button properties
            myStandardCommandBarButton.Caption = "My caption";
            myStandardCommandBarButton.Style = MsoButtonStyle.msoButtonCaption;
            myStandardCommandBarButton.BeginGroup = true;  // Separator line above button

            // Set the event handler
            myStandardCommandBarButton.Click += new _CommandBarButtonEvents_ClickEventHandler(myStandardCommandBarButton_Click);
         }
         catch (System.Exception ex)
         {
            MessageBox.Show(ex.ToString());
         }
      }

      public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
      {
         try
         {
            switch (disconnectMode)
            {
               case ext_DisconnectMode.ext_dm_HostShutdown:
               case ext_DisconnectMode.ext_dm_UserClosed:

                  if ((myStandardCommandBarButton != null))
                  {
                     // Remove the event handler
                     myStandardCommandBarButton.Click -= new _CommandBarButtonEvents_ClickEventHandler(myStandardCommandBarButton_Click);

                     // Delete the button
                     myStandardCommandBarButton.Delete(true);
                     myStandardCommandBarButton = null;
                  }

                  break;
            }
         }
         catch (System.Exception e)
         {
            MessageBox.Show(e.ToString());
         }
      }

      public void OnAddInsUpdate(ref Array custom)
      {
      }

      public void OnBeginShutdown(ref Array custom)
      {
      }

      private void myStandardCommandBarButton_Click(Microsoft.VisualStudio.CommandBars.CommandBarButton Ctrl, ref bool CancelDefault)
      {
         MessageBox.Show("Button with caption '" + Ctrl.Caption + "' clicked");
      }
   }
}
Language: VB.NET   Copy Code Copy Code (IE only)
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports System.Windows.Forms

Public Class Connect
   Implements Extensibility.IDTExtensibility2

   ' Variables for IDE and add-in instances
   Private applicationObject As EnvDTE.DTE
   Private addInInstance As EnvDTE.AddIn

   ' Buttons that will be created on built-in commandbars of Visual Studio
   ' We must keep them at class level to remove them when the add-in is unloaded
   Private myStandardCommandBarButton As CommandBarButton

   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

      Try

         applicationObject = CType(application, EnvDTE.DTE)
         addInInstance = CType(addInInst, EnvDTE.AddIn)

         Select Case connectMode

            Case ext_ConnectMode.ext_cm_UISetup

               ' Do nothing for this add-in with temporary user interface

            Case ext_ConnectMode.ext_cm_Startup

               ' The add-in was marked to load on startup
               ' Do nothing at this point because the IDE may not be fully initialized
               ' Visual Studio will call OnStartupComplete when fully initialized

            Case ext_ConnectMode.ext_cm_AfterStartup

               ' The add-in was loaded by hand after startup using the Add-In Manager
               ' Initialize it in the same way that when is loaded on startup
               AddTemporaryUI()

         End Select

      Catch e As System.Exception
         System.Windows.Forms.MessageBox.Show(e.ToString)
      End Try

   End Sub

   Public Sub OnStartupComplete(ByRef custom As System.Array) _
      Implements Extensibility.IDTExtensibility2.OnStartupComplete

      AddTemporaryUI()

   End Sub

   Public Sub AddTemporaryUI()

      Dim standardCommandBar As CommandBar
      Dim commandBars As CommandBars

      Try

         commandBars = DirectCast(applicationObject.CommandBars, CommandBars)

         ' Get the "Standard" toolbar
         standardCommandBar = commandBars.Item("Standard")

         ' Add a button to the built-in "Standard" toolbar
         myStandardCommandBarButton = DirectCast(standardCommandBar.Controls.Add(MsoControlType.msoControlButton), CommandBarButton)

         ' Change some button properties
         myStandardCommandBarButton.Caption = "My caption"
         myStandardCommandBarButton.Style = MsoButtonStyle.msoButtonCaption
         myStandardCommandBarButton.BeginGroup = True ' Separator line above button

         ' Set the event handler
         AddHandler myStandardCommandBarButton.Click, AddressOf myStandardCommandBarButton_Click

      Catch e As System.Exception
         MessageBox.Show(e.ToString)
      End Try

   End Sub

   Public Sub OnDisconnection(ByVal RemoveMode As Extensibility.ext_DisconnectMode, ByRef custom As System.Array) _
      Implements Extensibility.IDTExtensibility2.OnDisconnection

      Try

         Select Case RemoveMode

            Case ext_DisconnectMode.ext_dm_HostShutdown, ext_DisconnectMode.ext_dm_UserClosed

               If Not (myStandardCommandBarButton Is Nothing) Then

                  ' Remove the event handler
                  RemoveHandler myStandardCommandBarButton.Click, AddressOf myStandardCommandBarButton_Click

                  ' Delete the button
                  myStandardCommandBarButton.Delete()
                  myStandardCommandBarButton = Nothing

               End If

         End Select

      Catch e As System.Exception
         MessageBox.Show(e.ToString)
      End Try

   End Sub

   Public Sub OnBeginShutdown(ByRef custom As System.Array) _
      Implements Extensibility.IDTExtensibility2.OnBeginShutdown
   End Sub

   Public Sub OnAddInsUpdate(ByRef custom As System.Array) _
       Implements Extensibility.IDTExtensibility2.OnAddInsUpdate
   End Sub

   Private Sub myStandardCommandBarButton_Click(ByVal Ctrl As Microsoft.VisualStudio.CommandBars.CommandBarButton, _
      ByRef CancelDefault As Boolean)

      MessageBox.Show("Button with caption '" & Ctrl.Caption & "' clicked")

   End Sub

End Class

Related articles



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


Top