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

By , 26 Aug 2011
 

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)

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThanks!memberumeshfaq21-Mar-13 19:32 
QuestionCast Error messagememberMember 47353464-Feb-13 14:42 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130619.1 | Last Updated 26 Aug 2011
Article Copyright 2011 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid