// Create the command bar variables at the class level.
Office.CommandBar commandBar;
Office.CommandBarButton firstButton;
Office.CommandBarButton secondButton;
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)
{
// Add a commandbar named Test.
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.msoButtonCaption;
firstButton.Caption = "button 1";
firstButton.Tag = "button1";
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.msoButtonCaption;
secondButton.Caption = "button 2";
secondButton.Tag = "button2";
secondButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(ButtonClick);
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);
}