Click here to Skip to main content
15,867,568 members
Articles / Productivity Apps and Services / Microsoft Office

How to Add a Menu Item in Microsoft Office Word 7/10 Application Context Menu

Rate me:
Please Sign up or sign in to vote.
4.79/5 (10 votes)
28 Aug 2011CPOL2 min read 62.4K   1.6K   24   15
How to add a menu item in Microsoft Office Word 7/10 application context menu

Introduction

This is a very simple article, which is about how you can add a menu item in Microsoft Office Word 7/10 application context menu. Here we will discuss some custom event & delegates used for adding menu item.

The concept is simple; we will create an addIn project using Microsoft Visual Studio 2010. If you are not familiar with creating an addIn project, I would like to request you to read the article from the link below:

Background

Anyway, what are we actually doing in this article? Let’s make it clear first, we are trying to implement the functionalities listed below:

  1. We will create an AddIn for Microsoft Office Word.
  2. We will write few function/methods for adding a menu item in Microsoft Office Word application context menu.
  3. We will write a custom event for that item.
  4. We will write some text into the current open document.

That’s it, so let’s start to write code.

Using the Code

For this purpose, we will use a delegate ApplicationEvents4_WindowBeforeRightClickEventHandler
And a button event handler _CommandBarButtonEvents_ClickEventHandler.

Actually, we created two custom events:

  1. MyButton_Click()
  2. App_WindowBeforeRightClick()

The first event, i.e.,"MyButton_Click()" will just display a message box with a simple text message to ensure that you click on your custom menu item. The event "App_WindowBeforeRightClick()" will be fired when you right click on your Microsoft Word document. In code, we write a method "AddItem()" which is actually add the menu item into the Microsoft Office Word application context menu.

More information about ApplicationEvents4_WindowBeforeRightClickEventHandler could be found at this link.

More information about _CommandBarButtonEvents_ClickEventHandler could be found at this link.

The following figure A shows the output of the add-in program.

Figure A

ctx-menu.png

A sample code snippet is given below:

C#
public partial class ThisAddIn
    {
        _CommandBarButtonEvents_ClickEventHandler eventHandler;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            try
            {
                eventHandler = new _CommandBarButtonEvents_ClickEventHandler
				(MyButton_Click);
                Word.Application applicationObject =
			Globals.ThisAddIn.Application as Word.Application;
                applicationObject.WindowBeforeRightClick +=
		new Microsoft.Office.Interop.Word.ApplicationEvents4_
		WindowBeforeRightClickEventHandler(App_WindowBeforeRightClick);
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error: " + exception.Message);
            }
        }

        private void App_WindowBeforeRightClick
		(Microsoft.Office.Interop.Word.Selection Sel, ref bool Cancel)
        {
            try
            {
                this.AddItem();
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error: " + exception.Message);
            }
        }
        private void AddItem()
        {
            Word.Application applicationObject =
		Globals.ThisAddIn.Application as Word.Application;
            CommandBarButton commandBarButton =
		applicationObject.CommandBars.FindControl
		(MsoControlType.msoControlButton, missing, "HELLO_TAG", missing)
		as CommandBarButton;
            if (commandBarButton != null)
            {
                System.Diagnostics.Debug.WriteLine("Found button, attaching handler");
                commandBarButton.Click += eventHandler;
                return;
            }
            CommandBar popupCommandBar = applicationObject.CommandBars["Text"];
            bool isFound = false;
            foreach (object _object in popupCommandBar.Controls)
            {
                CommandBarButton _commandBarButton = _object as CommandBarButton;
                if (_commandBarButton == null) continue;
                if (_commandBarButton.Tag.Equals("HELLO_TAG"))
                {
                    isFound = true;
                    System.Diagnostics.Debug.WriteLine
			("Found existing button. Will attach a handler.");
                    commandBarButton.Click += eventHandler;
                    break;
                }
            }
            if (!isFound)
            {
                commandBarButton = (CommandBarButton)popupCommandBar.Controls.Add
		(MsoControlType.msoControlButton, missing, missing, missing, true);
                System.Diagnostics.Debug.WriteLine("Created new button, adding handler");
                commandBarButton.Click += eventHandler;
                commandBarButton.Caption = "Hello !!!";
                commandBarButton.FaceId = 356;
                commandBarButton.Tag = "HELLO_TAG";
                commandBarButton.BeginGroup = true;
            }
        }

        private void RemoveItem()
        {
            Word.Application applicationObject =
		Globals.ThisAddIn.Application as Word.Application;
            CommandBar popupCommandBar = applicationObject.CommandBars["Text"];
            foreach (object _object in popupCommandBar.Controls)
            {
                CommandBarButton commandBarButton = _object as CommandBarButton;
                if (commandBarButton == null) continue;
                if (commandBarButton.Tag.Equals("HELLO_TAG"))
                {
                    popupCommandBar.Reset();
                }
            }
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            Word.Application App = Globals.ThisAddIn.Application as Word.Application;
            App.WindowBeforeRightClick -=
		new Microsoft.Office.Interop.Word.ApplicationEvents4_
		WindowBeforeRightClickEventHandler(App_WindowBeforeRightClick);
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion

        //Event Handler for the button click
        private void MyButton_Click(CommandBarButton cmdBarbutton, ref bool cancel)
        {
            System.Windows.Forms.MessageBox.Show
			("Hello !!! Happy Programming", "Hello !!!");
            Globals.ThisAddIn.Application.Selection.InsertAfter
			("I love CodeProject" + Environment.NewLine);
            Globals.ThisAddIn.Application.Selection.InsertAfter
			("Author: " + "Md. Marufuzzaman" + Environment.NewLine);
            Globals.ThisAddIn.Application.Selection.InsertAfter
			("Thanks To : " +  Environment.UserName + Environment.NewLine);
            Globals.ThisAddIn.Application.Selection.InsertAfter
			("Current time is :" +  DateTime.Now.ToLongTimeString() +
			Environment.NewLine);
            RemoveItem();
        }
    }

History

  • 29th Aug 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionThank you Pin
Member 1119750415-Jul-15 21:18
Member 1119750415-Jul-15 21:18 
QuestionErrror in code Pin
Member 114361309-Feb-15 0:00
Member 114361309-Feb-15 0:00 
AnswerRe: Errror in code Pin
Md. Marufuzzaman9-Feb-15 3:07
professionalMd. Marufuzzaman9-Feb-15 3:07 
GeneralRe: Errror in code Pin
Member 114361309-Feb-15 21:13
Member 114361309-Feb-15 21:13 
GeneralRe: Errror in code Pin
Member 1119750415-Jul-15 21:17
Member 1119750415-Jul-15 21:17 
GeneralRe: Errror in code Pin
_Muro5-Apr-15 10:00
_Muro5-Apr-15 10:00 
QuestionRemoving Item on Shutdown Pin
Member 114361308-Feb-15 23:32
Member 114361308-Feb-15 23:32 
AnswerRe: Removing Item on Shutdown Pin
Md. Marufuzzaman9-Feb-15 3:05
professionalMd. Marufuzzaman9-Feb-15 3:05 
GeneralRe: Removing Item on Shutdown Pin
Member 114361309-Feb-15 21:15
Member 114361309-Feb-15 21:15 
GeneralRe: Removing Item on Shutdown Pin
Md. Marufuzzaman10-Feb-15 17:25
professionalMd. Marufuzzaman10-Feb-15 17:25 
Questionneed help Pin
odgiiv18-Nov-13 21:41
odgiiv18-Nov-13 21:41 
GeneralMy vote of 4 Pin
hebsiboy10-Feb-13 15:20
hebsiboy10-Feb-13 15:20 
GeneralRe: My vote of 4 Pin
Md. Marufuzzaman11-Feb-13 7:13
professionalMd. Marufuzzaman11-Feb-13 7:13 
GeneralReleasing COM objects and Ribbon-based context menus in Office 2010 Pin
Andrei Smolin7-Sep-11 23:49
Andrei Smolin7-Sep-11 23:49 
GeneralRe: Releasing COM objects and Ribbon-based context menus in Office 2010 Pin
Md. Marufuzzaman8-Sep-11 4:56
professionalMd. Marufuzzaman8-Sep-11 4:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.