Search code examples
c#outlookoffice-interopoffice-automation

Outlook Interop - insert string at cursor location


I am currently working with the Outlook interop to inject some text at the cursor position.

I have a working solution for injecting into an email and calendars body, but I cannot seem to find anywhere which will let me find the cursor location (focused element).

I am using the CurrentItem to ensure I have the correct item, but would like to know what item is focused so in MailItem is it: body, subject, to, cc, and bcc. then for CalendarItem is the focused body or title.

is there a way from CurrentItem to find where the keyboard/cursor focus is?

My current working solution for injection to the body:

                var outlookAsObject = Marshal.GetActiveObject("Outlook.Application");
                _outlook = (Microsoft.Office.Interop.Outlook.Application) outlookAsObject;
                _log.Info("Outlook Application found");
                var activeElement = _outlook.ActiveInspector().CurrentItem;
                _log.Info($"outlook injector: Current item is mailItem: {activeElement is 
                    MailItem}");
                    Inspector myInspector = activeElement.GetInspector;
                    _log.Info("outlook injector: inspector obtained");
                    Document wdDoc = myInspector.WordEditor;
                    _log.Info("outlook injector: document obtained");
                    var wdRng = wdDoc.Application.Selection.Range;
                    _log.Info($"outlook injector range is: {wdRng}");
                    wdRng.InsertAfter(text);
                    _log.Info("outlook injector: Text sent");

               

Solution

  • There is no trivial way to get the job done. The Outlook extensibility model doesn't provide that information out of the box.

    The best what you could do is to use Windows API for subclassing the Outlook window. Also you may try using the Accessibility API.