Change outlook mailitem selection c#

2019-05-24 16:04发布

问题:

I want to select a mailItem from my outlook add-in. I know how to display a mailitem from c# but I need to select it inside the outlook window itself.

Display a mailitem:

mailItem.Display();

I am using the Outlook 2010 Add-in.

Anybody has any idea on how to do this?

回答1:

Use Explorer.ClearSelection() and then Explorer.AddToSelection(). You should use Explorer.IsItemSelectableInView() before calling AddToSelection() to ensure the item you want to select exists in the current explorer view.

Application.ActiveExplorer() will give you the current active explorer if it exists.

Here is a sample snippet taken from here (slightly modified to check IsItemSelectableInView).

Outlook._Explorer explorer = OutlookApp.ActiveExplorer();  // get active explorer
explorer.ClearSelection(); // remove current selection
Outlook.NameSpace ns = OutlookApp.Session; 
object item = ns.GetItemFromID(entryId, Type.Missing); // retrieve item
if (explorer.IsItemSelectableInView(item)) // ensure item is in current view
  explorer.AddToSelection(item); // change explorer selection
else
  // TODO: change current view so that item is selectable
Marshal.ReleaseComObject(item); 
Marshal.ReleaseComObject(ns); 
Marshal.ReleaseComObject(explorer); 

To change the current Explorer view you can use Explorer.CurrentFolder or Explorer.CurrentView