以程式設計方式確定目前的 Outlook 項目

此範例使用 Explorer.SelectionChange 事件顯示目前資料夾的名稱以及所選項目的某些相關資訊。 程式碼接著會顯示所選項目。

適用對象: 本主題資訊適用於 Outlook 的 VSTO 增益集專案。 如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能

範例

Outlook.Explorer currentExplorer = null;

private void ThisAddIn_Startup
    (object sender, System.EventArgs e)
{
    currentExplorer = this.Application.ActiveExplorer();
    currentExplorer.SelectionChange += new Outlook
        .ExplorerEvents_10_SelectionChangeEventHandler
        (CurrentExplorer_Event);
}

private void CurrentExplorer_Event()
{
    Outlook.MAPIFolder selectedFolder =
        this.Application.ActiveExplorer().CurrentFolder;
    String expMessage = "Your current folder is "
        + selectedFolder.Name + ".\n";
    String itemMessage = "Item is unknown.";
    try
    {
        if (this.Application.ActiveExplorer().Selection.Count > 0)
        {
            Object selObject = this.Application.ActiveExplorer().Selection[1];
            if (selObject is Outlook.MailItem)
            {
                Outlook.MailItem mailItem =
                    (selObject as Outlook.MailItem);
                itemMessage = "The item is an e-mail message." +
                    " The subject is " + mailItem.Subject + ".";
                mailItem.Display(false);
            }
            else if (selObject is Outlook.ContactItem)
            {
                Outlook.ContactItem contactItem =
                    (selObject as Outlook.ContactItem);
                itemMessage = "The item is a contact." +
                    " The full name is " + contactItem.Subject + ".";
                contactItem.Display(false);
            }
            else if (selObject is Outlook.AppointmentItem)
            {
                Outlook.AppointmentItem apptItem =
                    (selObject as Outlook.AppointmentItem);
                itemMessage = "The item is an appointment." +
                    " The subject is " + apptItem.Subject + ".";
            }
            else if (selObject is Outlook.TaskItem)
            {
                Outlook.TaskItem taskItem =
                    (selObject as Outlook.TaskItem);
                itemMessage = "The item is a task. The body is "
                    + taskItem.Body + ".";
            }
            else if (selObject is Outlook.MeetingItem)
            {
                Outlook.MeetingItem meetingItem =
                    (selObject as Outlook.MeetingItem);
                itemMessage = "The item is a meeting item. " +
                     "The subject is " + meetingItem.Subject + ".";
            }
        }
        expMessage = expMessage + itemMessage;
    }
    catch (Exception ex)
    {
        expMessage = ex.Message;
    }
    MessageBox.Show(expMessage);
}

編譯程式碼

這個範例需要:

  • Microsoft Office Outlook 中的約會、連絡人和電子郵件項目。