Outlook 2010插件C#公共方法

non*_*ame 4 c# outlook visual-studio-2010 visual-studio outlook-addin

我需要开发一个Outlook 2010加载项,我是Visual Studio和C#的新手,因为我主要使用PHP和JavaScript.我正在使用Visual Studio 2010,并且我使用内置的Outlook 2010加载项模板创建了一个项目.考虑下面的代码:

// file ThisAddIn.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;


namespace OutlookAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
        }

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

        public string displayCount()
        {
            Outlook.MAPIFolder inbox = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            Outlook.Items unreadItems = inbox.Items.Restrict("[Unread]=true");

            return string.Format("Unread items in Inbox = {0}", unreadItems.Count);
        }

        #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
    }
}

// file Ribbon1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;

namespace OutlookAddIn1
{
    public partial class Ribbon1
    {
        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            // call ThisAddIn.displayCount() here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,如何在Ribbon1类或其他任何地方调用ThisAddIn类中的公共方法?我知道我需要一个对象引用,但是如何找到实例的名称?我看不到在现有文件中的任何位置创建ThisAddIn的实例.或者我是否误解了这个概念,它应该以其他方式完成?我将不胜感激任何有关创建Office加载项的建议或链接.

小智 6

在VSTO项目中,Globals可以在项目的任何位置使用自动生成的密封类.Globals包含许多公共或内部静态属性,其中一个属性ThisAddIn(类型ThisAddIn,足够适当).而不是上述代码,您的代码将如下所示.

在Ribbon1.cs中:

public void DoSomethingOnRibbon(Office.IRibbonControl control)
{
    string count = Globals.ThisAddIn.displayCount();
    ...
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.