Search code examples
c#outlookoffice-interop

C# Outlook Acces CommandBar Programmatically


I'm trying to access to some buttons on my Outlook Ribbon Programmatically. So i am using:

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
CommandBar command = app.ActiveExplorer().CommandBars.OfType<CommandBar>().First();
CommandBarControl button = command.Controls.OfType<CommandBarControl>().Where(x => x.Caption == "label of my button").First();
button.Execute();

The problem is every CommandBars only return 1 Control... How can i access to all Controls inside a Ribbon ?

Thanks


Solution

  • As Eugene mentioned, you can use the Accessibility API. If using Redemption is an option (I am its author), it exposes SafeExplorer and SafeInspector objects that provide access to the ribbon controls and allow to execute their default actions. The example below (VB script) executes the "OneNote" button on the "Home" ribbon:

     set sExplorer = CreateObject("Redemption.SafeExplorer")
     sExplorer.Item = Application.ActiveExplorer
     set Ribbon = sExplorer.Ribbon
     oldActiveTab = Ribbon.ActiveTab
     Ribbon.ActiveTab = "Home"
     set Control = Ribbon.Controls("OneNote")
     Control.Execute
     Ribbon.ActiveTab = oldActiveTab 'restore the active tab