Outlook 2010插件C#公共方法

4

我需要开发一个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
        }
    }
}

问题是,如何从ThisAddIn类中的Ribbon1类或任何其他地方调用公共方法?我知道我需要一个对象引用,但我怎么能找出实例的名称?我在现有文件中看不到ThisAddIn的任何实例被创建。或者我是否误解了概念,应该用其他方式完成?我将感谢任何关于创建Office插件的建议或信息链接。
2个回答

6
在VSTO项目中,有一个名为Globals的自动生成的封闭类,可以从项目内的任何位置访问。 Globals包含许多公共或内部静态属性,其中之一是ThisAddIn(类型为ThisAddIn)。 您的代码将如下所示:

在Ribbon1.cs中:

public void DoSomethingOnRibbon(Office.IRibbonControl control)
{
    string count = Globals.ThisAddIn.displayCount();
    ...
}

希望这有所帮助。

我在ThisAddIn类中有一个方法,我可以从同一解决方案中的另一个项目中访问它,但运行时出现错误Globals.ThisAddIn为空,我该如何解决这个问题? - N Khan

3
我使用一个静态成员变量(并伴随着一个静态的getter方法),在插件初始化时设值,然后我可以从代码库的任何地方访问它,命名为Core(根据需要选择名称)。当然,如果可用的话,我会尝试在上下文中传递插件对象,但有时很难实现。

该类由插件容器/加载器自动实例化(实际上作为COM组件公开,至少在ADX中是这样的:)。

编码愉快。


代码可能如下所示:

// inside ThisAddIn class
public static ThisAddIn Active {
  get;
  private set;
}

// inside ThisAddIn_Startup
Active = this;

// later on, after add-in initialization, say in Ribbon1.button1_Click
ThisAddIn.Active.displayCount();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接