Практическое руководство. Создание меню Office программными средствами
Обновлен: Ноябрь 2007
Применение |
---|
Сведения, приведенные в данном разделе, относятся только к указанным проектам Visual Studio Tools for Office и версиям Microsoft Office. Тип проекта
Версия Microsoft Office
Дополнительные сведения см. в разделе Доступность функций по типам приложений и проектов. |
Рассматриваемый ниже пример создает меню New Menu в строке меню Microsoft Office Excel 2003. Новое меню помещается перед меню Справка. и содержит одну команду. При выборе этого пункта меню в ячейку Sheet1 будет вставлен текст.
Пример настройки пользовательского интерфейса Microsoft Office Word 2003 см. в разделах Практическое руководство. Создание панелей инструментов Office программными средствами и Пошаговое руководство. Создание контекстного меню для закладок.
Добавьте в класс ThisWorkbook следующий код.
![]() |
---|
При добавлении обработчиков событий элементов управления необходимо устанавливать их свойство Tag. Office использует свойство Tag, чтобы отслеживать обработчики событий данной панели команд CommandBarControl. Если свойство Tag не установлено, события не будут правильно обрабатываться. |
![]() |
---|
Переменные, представляющие пункты меню, следует объявлять на уровне класса, а не в методе, в котором создаются эти пункты меню. Благодаря этому переменные меню будут оставаться в области видимости в течение всего времени работы приложения. В противном случае элемент меню удаляется в процессе сборки мусора, и его обработчик событий не будет вызываться. |
Пример
' Declare the menu variable at the class level.
Private WithEvents menuCommand As Office.CommandBarButton
Private menuTag As String = "A unique tag"
' Call AddMenu from the Startup event of ThisWorkbook.
Private Sub ThisWorkbook_Startup(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Startup
CheckIfMenuBarExists()
AddMenuBar()
End Sub
' If the menu already exists, remove it.
Private Sub CheckIfMenuBarExists()
Try
Dim foundMenu As Office.CommandBarPopup = _
Me.Application.CommandBars.ActiveMenuBar.FindControl( _
Office.MsoControlType.msoControlPopup, System.Type.Missing, menuTag, True, True)
If foundMenu IsNot Nothing Then
foundMenu.Delete(True)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
' Create the menu, if it does not exist.
Private Sub AddMenuBar()
Try
Dim menuBar As Office.CommandBar = Application.comm.CommandBars.ActiveMenuBar
Dim menuCaption As String = "Ne&w Menu"
If menuBar IsNot Nothing Then
Dim cmdBarControl As Office.CommandBarPopup = Nothing
Dim controlCount As Integer = menuBar.Controls.Count
' Add the new menu.
cmdBarControl = CType(menuBar.Controls.Add( _
Type:=Office.MsoControlType.msoControlPopup, Before:=controlCount, Temporary:=True), _
Office.CommandBarPopup)
cmdBarControl.Caption = menuCaption
' Add the menu command.
menuCommand = CType(cmdBarControl.Controls.Add( _
Type:=Office.MsoControlType.msoControlButton, Temporary:=True), _
Office.CommandBarButton)
With menuCommand
.Caption = "&New Menu Command"
.Tag = "NewMenuCommand"
.FaceId = 65
End With
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
' Add text to cell A1 when the menu is clicked.
Private Sub menuCommand_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, _
ByRef CancelDefault As Boolean) Handles menuCommand.Click
Globals.Sheet1.Range("A1").Value2 = "The menu command was clicked."
End Sub
// Declare the menu variable at the class level.
private Office.CommandBarButton menuCommand;
private string menuTag = "A unique tag";
// Call AddMenu from the Startup event of ThisWorkbook.
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
CheckIfMenuBarExists();
AddMenuBar();
}
// If the menu already exists, remove it.
private void CheckIfMenuBarExists()
{
try
{
Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)
this.Application.CommandBars.ActiveMenuBar.FindControl(
Office.MsoControlType.msoControlPopup, System.Type.Missing, menuTag, true, true);
if (foundMenu != null)
{
foundMenu.Delete(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// Create the menu, if it does not exist.
private void AddMenuBar()
{
try
{
Office.CommandBarPopup cmdBarControl = null;
Office.CommandBar menubar = (Office.CommandBar)Application.CommandBars.ActiveMenuBar;
int controlCount = menubar.Controls.Count;
string menuCaption = "&New Menu";
// Add the menu.
cmdBarControl = (Office.CommandBarPopup)menubar.Controls.Add(
Office.MsoControlType.msoControlPopup, missing, missing, controlCount, true);
if (cmdBarControl != null)
{
cmdBarControl.Caption = menuCaption;
// Add the menu command.
menuCommand = (Office.CommandBarButton)cmdBarControl.Controls.Add(
Office.MsoControlType.msoControlButton, missing, missing, missing, true);
menuCommand.Caption = "&New Menu Command";
menuCommand.Tag = "NewMenuCommand";
menuCommand.FaceId = 65;
menuCommand.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(
menuCommand_Click);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
// Add text to cell A1 when the menu is clicked.
private void menuCommand_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
Globals.Sheet1.Range["A1", missing].Value2 = "The menu command was clicked.";
}
См. также
Задачи
Практическое руководство. Создание панелей инструментов Office программными средствами
Пошаговое руководство. Создание контекстного меню для закладок
Основные понятия
Настройка пользовательского интерфейса Office
Общие сведения о необязательных параметрах в решениях Office