Click here to Skip to main content
Click here to Skip to main content

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

, 28 Aug 2011
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
A highly experienced leader with successful track record of software development, product innovations, brand management and corporate communication etc. Some successful product innovations have also achieved and awards “Most Valuable Professional” (MVP) at 2010 and 2011 by codeproject.com and also selected as a mentor of codeproject.com. Published over 100 technical articles in various software development resource sites (i.e., codeprojetc.com, Microsoft MSDN, and IEEE & IBM (In progress)) and various IT Forums, Blogs etc.
 
Over ten years of professional experiences in ICT field having extensive experience in formulating corporate vision and long term strategy. Leading development related functions including design, development, services, data management and analytics, customer experience management, content services, digital analytics and optimization.
 
An individual with results-driven approach and relentless in pursuit of excellence from a business and organizational standpoint. Believes in transparency, commitment and teamwork.
 
Expertise: Software/Solution Architect, SaaS platform base application, Large scale win32/web based business software solutions, enterprise applications, integration, etc.
 
Technologies/Tools: Microsoft.Net version 05/08/10/12, Microsoft SQL Server version 7/2K/05/08/12 , Oracle version 10/11, MySql version 5.1, 5.5, PS2, Visual C#, R, VB.NET, ASP.NET, PHP, API, MVC, WebAPI , Add-In Visual Basic etc.,. I have also more than two years’ of strong experience in mobile-VAS (platform development).
 
Points of Interest: Technology and research & development especially focused on business functionalities and social business areas as well, few stuff including:
 
1.R&D on new techniques as required to increase business revenue.
2.Urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc., using innovative technical solutions.
3.Research and innovative product development.
4.Etc.
Follow on   Twitter   LinkedIn

Comments and Discussions

 
Questionneed help Pinmemberodgiiv18-Nov-13 21:41 
GeneralMy vote of 4 Pinmemberhebsiboy10-Feb-13 15:20 
GeneralRe: My vote of 4 PinmentorMd. Marufuzzaman11-Feb-13 7:13 
GeneralReleasing COM objects and Ribbon-based context menus in Office 2010 PinmemberAndrei Smolin7-Sep-11 23:49 
GeneralRe: Releasing COM objects and Ribbon-based context menus in Office 2010 PinmvpMd. Marufuzzaman8-Sep-11 4:56 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 28 Aug 2011
Article Copyright 2011 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid