'Outlook plugin (VSTO) - Set focus back to editor after range's function InsertAfter

My outlook plugin (FormRegion) insert text into mail body on demand (user clicks a button) - the text is inserted by the "InsertAfter" function (Range's function). After the click, the focus is on the button so the user needs to click back in the editor in order to continue writing.

How can I set the focus back to the editor?

Thank you.



Solution 1:[1]

After trying every possible solutions, I noticed that the mail body loses the focus when messagebox \ new form is being initiated, and when it get closed - the focus is back to the mail body.

So I came up with some dirty workaround - I created a new form with 0% opacity which close after few miliseconds, that way the focus is back to the mail body immediately.

dirty, but works well.

Solution 2:[2]

You can try to use the Activate method of the Document class from the Word object model.

Or just use the SetFocus function which sets the keyboard focus to the specified window. The window must be attached to the calling thread's message queue.

The SetFocus function sends a WM_KILLFOCUS message to the window that loses the keyboard focus and a WM_SETFOCUS message to the window that receives the keyboard focus. It also activates either the window that receives the focus or the parent of the window that receives the focus.

Solution 3:[3]

You would need to find the HWND of the editor control and call SetActiveWindow / SetFocus / ShowCaret Windows API functions. Things get a lot more interesting if you are running out-of-proc (not in your case).

If using Redemption (I am its author) is an option, it exposes the SafeInspector object and the SafeInspector.FocusEditor method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shushi
Solution 2 Eugene Astafiev
Solution 3