« Speaking in Gibberish and Writing Constantly | Main | VBA and Visual Basic For ... to ... statements »

VBA to VSTO Tutorial Part Two - Adding a Command Bar and Buttons

In my previous tutorial on using VSTO to create a Microsoft Project Add-in, I covered what is necessary to create an Add-in which displays a simple form but most of the time we don't want the form to show up every time. A better way to do this is to add a tool bar (aka: CommmandBar) and some buttons / icons (aka: CommandBarButtons). This way if your add-in is installed it can have its own toolbar which users can click if they want to perform some action or display a form. Project 2003 and Project 2007 still use the same sort of command bar and command bar button interface as earlier versions of Office Applications. If you are creating an Add-in for Excel 2007 or Word 2007 you will be working with the new Ribbon interface. I'll write about that when Project catches up with that interface...

Adding a Command Bar / Tool Bar to the Microsoft Project Interface

This installment covers how to add a command bar and a couple of buttons. If you have not read the first tutorial you should go back and read it here.

The first thing to do is to define the objects we are going to use. We want them available from any other object in our add-in so define them right at the top. The command bar is going to use two buttons only. One will display a form with buttons and other controls. The other will display a form with "About" information on it.

Public Class ThisAddIn
Dim commandBar as Office.CommandBar
Dim firstButton as Office.CommandBarButton
Dim secondButton as Office.CommandBarButton

A Subprocedure to Add the Command Bar

The next thing to do is to add the command bar. I've put this in its own subprocedure so tha I can easily reuse the code in another add-in or if I want to add multiple command bars to the same add-in. It takes a string barName as the name of the bar. This code should be really simple, but we want to make sure that we have the latest version of the command bar so first we check to see if the bar exists. If it does then we delete it and add it again.

Private Sub addToolBar(ByVal barName As String)
Try
commandBar = Application.CommandBars(barName)
Catch ex As ArgumentException
' Toolbar does not exist so we should create it later
End Try
If Not commandBar Is Nothing Then
Application.CommandBars(barName).Delete()
End If

Application.CommandBars.Add(barName, 1, False, False)
commandBar = Application.CommandBars(barName)
End Sub

Adding Buttons to the Command Bar

The next step is to add the buttons to the toolbar. Once again I'm writing this as a subprocedure so that I can easily reuse it or modify it. The names of the buttons are hardcoded but you could add them as a parameter as well if you feel like it.

Private Sub addButton(ByVal cBarName As String)
commandBar = Application.CommandBars(cBarName)
Try
' Add a button to the command bar and create an event handler.
firstButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
firstButton.Style = Office.MsoButtonStyle.msoButtonCaption
firstButton.Caption = "Monte Carlo"
firstButton.Tag = "montecarlo"
AddHandler firstButton.Click, AddressOf Button1Click
' Add a second button to the command bar and create an event handler.
secondButton = CType(commandBar.Controls.Add(1), Office.CommandBarButton)
secondButton.Style = Office.MsoButtonStyle.msoButtonCaption
secondButton.Caption = "about"
secondButton.Tag = "about"
AddHandler secondButton.Click, AddressOf Button2Click
commandBar.Visible = True Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Adding Handlers for Button Clicks

If we run these two subprocedures we get a tool bar and add two buttons to it. Next we need to set up what the buttons should do. Similar to any button control, we use an event handler (defined above). The first button will create and show our master form.

Private Sub Button1Click(ByVal ctrl As Office.CommandBarButton, ByRef Cancel As Boolean)
Dim monteCarlo As New fmMonteCarlo
monteCarlo.Show()
End Sub

We do a similar thing for the "About" form.

Private Sub Button2Click(ByVal ctrl As Office.CommandBarButton, ByRef Cancel As Boolean)
Dim aBox As New AboutBox1
aBox.Show()
End Sub

Run when Add-in Starts

The next thing to do is to make sure that these subprocedures run when the add-in starts. We put the two subprocedures in the "Startup" event for the addin.

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
...
addToolBar("Monte Carlo")
addButton("Monte Carlo")
...
End Sub

Cleaning Up at the End

The very final thing to do is clean up after ourselves. If a user wants to remove or unload the add-in we would expect that the command bar would go away as well. To do this we just delete the command bar in the Shutdown event for the Add-in.

Private Sub ThisAddIn_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
Application.CommandBars("Monte Carlo").Delete()
...
End Sub

With this and the previous tutorial you should be able to get through the initial hurdles that you face moving from VBA to VSTO and should be able to create and deploy a Project 2007 Add-in that adds a command bar and displays a form. And you should be able to create a form with some simple controls and code. From this point on, coding in visual basic using Visual Studio 2008 is very similar to using VBA.

RELATED POSTS
  • Microsoft Project Undo Levels and Macros
  • Setting Microsoft Project Level Custom fields using VBA
  • Iterating through Microsoft Project Subprojects
  • VBA and Visual Basic For ... to ... statements
  • Making the move from VBA to VSTO in Microsoft Project
  • Office VBA for Mac After 2008
  • Analyze Microsoft Project Resource Usage Data In Excel
  • VBA Writing to a text file (MS Project, Excel)
  • MS Project VBA - Trim Function
  • Using a ComboBox in a Microsoft Project Userform

  • Comments (3)

    Jabez Kurian:

    Hi,

    Thanks for posting this article which has helped me in creating a toolbar button programattically. Now that Iam done with creation of button, I would also like to set the button image to any of the available images.

    Please suggest on how to achieve this functionality.

    Thank you.

    - Jabez

    roy:

    Hi, Gr8 article. Do u have a sample code in C#. the move from vb to c# is killing me.

    Thanks.
    ----------------
    Sorry, but no. -Jack

    Venkat:

    Hi,

    Thanks for the article. helped me creating a command bar.
    Here is the c# code and setting up image for the button.

    public partial class ThisAddIn
    {
    Office.CommandBar commandBar;
    Office.CommandBarButton firstButton;
    Office.CommandBarButton secondButton;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {

    AddToolbar();
    }

    private void AddToolbar()
    {
    try
    {
    commandBar = Application.CommandBars["Test"];
    }
    catch (ArgumentException e)
    {
    // Toolbar named Test does not exist so we should create it.
    }

    if (commandBar == null)
    {
    commandBar = Application.CommandBars.Add("Test", 1, missing, true);
    }

    try
    {
    // Add a button to the command bar and an event handler.
    firstButton = (Office.CommandBarButton)commandBar.Controls.Add(1, missing, missing, missing, missing);
    firstButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
    firstButton.Caption = "Button 1";
    firstButton.Tag = "Button 1";
    firstButton.TooltipText = "Button 1";
    firstButton.Picture = (IPictureDisp)AxHost2.GetIPictureDispFromPicture(Resources.Access);

    firstButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(ButtonClick);

    // Add a second button to the command bar and an event handler.
    secondButton = (Office.CommandBarButton)commandBar.Controls.Add(1, missing, missing, missing, missing);
    secondButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
    secondButton.Caption = "button 2";
    secondButton.Tag = "button2";
    secondButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(ButtonClick);
    secondButton.Picture = (IPictureDisp)AxHost2.GetIPictureDispFromPicture(Resources.Access);
    commandBar.Visible = true;
    }
    catch (ArgumentException e)
    {
    MessageBox.Show(e.Message);
    }
    }

    // Handles the event when a button on the new toolbar is clicked.
    private void ButtonClick(Office.CommandBarButton ctrl, ref bool cancel)
    {
    MessageBox.Show("You clicked: " + ctrl.Caption);
    }
    }

    Post a comment

    (Comments are moderated to fight SPAM and will be published after I have a chance to approve them. Thanks for waiting.)

    About

    The previous article is Speaking in Gibberish and Writing Constantly.

    The next article is VBA and Visual Basic For ... to ... statements.

    Current articles are in the main index page and you can find a complete list of articles in the archives.

    Creative Commons License
    This weblog is licensed under a Creative Commons License.
    Powered by
    Movable Type 3.34