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

Outlook 2007 Add-in Using Microsoft Visual C#.NET- Part 2

, 26 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How we can communicate with the Microsoft Office Outlook using “Microsoft.Office.Interop.Outlook” delegate & event.

Table of Contents

  • Introduction
  • What we learn?
    • How to create an Outlook7 AddIn project
    • How to create category tag
    • How to Add menu Item into Outlook application context menu
  • Reference
  • Conclusion

Introduction

Last year, I wrote an article which is about “Outlook 2007 Add-in Using Microsoft Visual C#.NET” where we discussed how to develop an add-in for Microsoft Office Outlook 2007 to help a fictitious company. How to add custom menus, toolbar command button, custom tabs (Outlook 2007), work with ribbon and custom forms as well. Anyway, if you are a beginner, I would like to request you to please read my first article from the link below:

Well, if you familiar with that, then I would say go ahead.

*** Please note that I used Microsoft Visual Studio 2010, Framework 4.0.

What We Learn

In this article, we will not discuss about creating custom menus, toolbar command button, custom tabs, etc. Our main objective will be how we can communicate with the Microsoft Office Outlook using “Microsoft.Office.Interop.Outlook” delegate & event. Well let’s think we want to create an Outlook AddIn which will be able to do the following:

  • Objective - 1. Inform you when new mail arrives
  • Objective - 2. Display item location (path) when you click on a particular object like an email or subfolders, etc.
  • Objective - 3. Able to create new category tags.

I think it’s pretty interesting! Isn’t it? So what are we waiting for, let's start creating this addIn. More information on the Outlook API delegate & event could be found at this link.

Create an Outlook7 AddIn project

I hope that you have the basic knowledge on how to create a Microsoft Office Outlook AddIn project using Microsoft Visual Studio 2008 or its May 2010. So if you are not comfortable with that, I would like to request you to read the first part of this article from this link.

Well, let’s implement our objective. Create a Microsoft Office Outlook AddIn project from your Microsoft Visual Studio 2008 / 2010. Now we will write our first code to achieve our first task, i.e., informing you when new emails arrive. But how could we do that?

Objective 1. Inform you when new mail arrive

Well, we will use a delegate (ApplicationEvents_11_NewMailEventHandler Delegate) for that. You might have a question as to what this delegate does? Simply I can say that this is a delegate for an event in the corresponding object. The following code snippets example will fulfill our first objective.

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.NewMail += new ApplicationEvents_11_NewMailEventHandler(EmailArrived);
}

private void EmailArrived()
{
    MessageBox.Show("Hello !!! You have new emails. ");
}

The following figure A shows the output of the code above.

Figure A

new-mail-arrive.png

More information about ApplicationEvents_11_NewMailEventHandler Delegate could be found at this link.

Objective -2. Display item location (path) when clicking on a particular object like an email or subfolders, etc.

To obtain pacific location / path of an item, we will use another delegate (ApplicationEvents_11_ItemLoadEventHandler) for that. The below code snippet does this job for us:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.ItemLoad += 
           new ApplicationEvents_11_ItemLoadEventHandler(GetMailItemLocation);
}
private void GetMailItemLocation(object Item)
{	
    if (outlookObj.ActiveExplorer().CurrentFolder != null)
    {
      var mailItem = outlookObj.ActiveExplorer().CurrentFolder;
      Outlook.MAPIFolder oFolder = (Outlook.MAPIFolder)mailItem;
      MessageBox.Show("Hello !!! I am located at 
		{" + oFolder.FolderPath.ToString() + "}");
    }
}

The following figure B shows the output of the code above.

Figure B

item-location.png

More information about ApplicationEvents_11_ItemLoadEventHandler could be found at this link.

How to Create a Category Tag

Objective 3. Able to create new category tags

Okay, great! Now we will create a custom category, well Microsoft Office Outlook has few number of categories, so we need to apply a little check that the category we are creating already exists or not. Anyway, the code below will create a category.

  private void AddCategory(string categoryName, object olCategoryColor)
        {
            if (AllowToAddCategory(categoryName))
            {
                outlookObj = new Outlook.Application();
                Outlook.Categories olCategoryList = outlookObj.Session.Categories;
                olCategoryList.Add(categoryName, 
			Outlook.OlCategoryColor.olCategoryColorDarkOrange);
                MessageBox.Show("Category [ " + categoryName  + " ] 
			successfully created.");
                this.Close();
            }
            else
            {
                MessageBox.Show("This category already exist.");
            }
        }
       
        private bool AllowToAddCategory(string categoryName)
        {
            bool retValue = false;
            outlookObj = new Outlook.Application();
            Outlook.Categories olCategoryList = outlookObj.Session.Categories;

            foreach (Outlook.Category category in olCategoryList)
            {
                if (category.Name.Equals(categoryName))
                {
                    retValue = false;
                    return retValue;
                }
                else { retValue = true; }
            }

            return retValue;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (this.textBoxCategory.Text != null)
            {
                this.AddCategory(textBoxCategory.Text, null);
            }
        }

The following figure C shows the input category name to create a new category.

Figure C

create-category.png

The following figure D, shows the output of our new category.

Figure D

display-category.png

How to Add menu Item into Outlook Application Context Menu

To add an item into Microsoft Office Outlook context menu, we need to use the ApplicationEvents_11_ItemContextMenuDisplayEventHandler delegate. More information on ApplicationEvents_11_ItemContextMenuDisplayEventHandler could be found at this link.

The below code snippets will add the custom menu item into the application context menu.

 private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            olInspectors = this.Application.Inspectors;
            olInspectors.NewInspector += 
		new InspectorsEvents_NewInspectorEventHandler(GetMailItemEntryId_Click);
             outlookObj = new Outlook.Application();
            this.Application.ItemContextMenuDisplay += 
		new Outlook.ApplicationEvents_11_ItemContextMenuDisplayEventHandler
			(Application_ItemContextMenuDisplay);
            this.Application.NewMail += 
		new ApplicationEvents_11_NewMailEventHandler(EmailArrived);
            this.Application.ItemLoad += 
		new ApplicationEvents_11_ItemLoadEventHandler(GetMailItemLocation);
          }

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

        #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

        #region Private Methods

        private void Application_ItemContextMenuDisplay
		(Office.CommandBar CommandBar, Outlook.Selection Selection)
        {
            if (Selection[1] is Outlook.MailItem)
            {
                this.CustomContextMenu(CommandBar, Selection);
                this.CustomContextCategoryMenu(CommandBar, Selection);
            }
        }

        private void CustomContextCategoryMenu
		(Office.CommandBar CommandBar, Outlook.Selection Selection)
        {

            Office.CommandBarButton customContextMenuTag =
                 		(Office.CommandBarButton)CommandBar.Controls.Add
					(Office.MsoControlType.msoControlButton
                                            , Type.Missing
                                            , Type.Missing
                                            , Type.Missing
                                            , true);

            customContextMenuTag.Caption = "Create category";
            customContextMenuTag.FaceId = 445;
            customContextMenuTag.Click += 
		new Office._CommandBarButtonEvents_ClickEventHandler
		(customContextMenuCategoryTag_Click);

        }
   
        private void CustomContextMenu(Office.CommandBar CommandBar, 
					Outlook.Selection Selection)
        {

            Office.CommandBarButton customContextMenuTag =
                          (Office.CommandBarButton)CommandBar.Controls.Add
				(Office.MsoControlType.msoControlButton
                                     , Type.Missing
                                     , Type.Missing
                                     , Type.Missing
                                     , true);

            customContextMenuTag.Caption = "My Menu";
            customContextMenuTag.FaceId = 446;
            customContextMenuTag.Click += 
	   new Office._CommandBarButtonEvents_ClickEventHandler(customContextMenuTag_Click);
        }
        #endregion

        #region Events Handler
        private void customContextMenuTag_Click
		(Office.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            MessageBox.Show("Hello !!! Happy Programming. ");
        }

        private void customContextMenuCategoryTag_Click
		(Office.CommandBarButton Ctrl, ref bool CancelDefault)
        {

            CategoryDialog categoryDialog = new CategoryDialog();
            categoryDialog.ShowDialog();
        }

        #endregion
    }

The following figure E shows the created menu items.

Figure E

context-menu.png

Reference

  • Microsoft Development Network

Conclusion

I hope this might be helpful to you!!!

History

  • 27th 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

 
GeneralMy vote of 5 PinprofessionalAgent__00719-Oct-14 23:21 
Questioncustom ribbons toggle button do not unchecked (default state) after checking it on mail send button click Pinmemberzakirhos2-Nov-13 19:18 
QuestionThanks! Pinmemberumeshfaq21-Mar-13 19:32 
QuestionCast Error message PinmemberMember 47353464-Feb-13 14:42 

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
Web02 | 2.8.141015.1 | Last Updated 26 Aug 2011
Article Copyright 2011 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid