I am wanting to bring Outlook's main window to the front, from within a VSTO add-in. I tried the approaches described in the various answers to this question, and it just doesn't seem to work, at least for Outlook 2021.
I get the Outlook main window's handle (which I verified using spy++ and appears to be correct), using either
Process.GetProcessesByName("outlook").FirstOrDefault().MainWindowHandle
or
(Globals.ThisAddIn.Application.ActiveExplorer() as IOleWindow).GetWindow()
(both yield the same result).
Then I try to bring the window to the front (probably some redundant calls in there, I was just trying everything I could to get this to work):
ShowWindow(proc.MainWindowHandle, SW_SHOWNORMAL);
ShowWindow(proc.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(proc.MainWindowHandle);
SwitchToThisWindow(proc.MainWindowHandle, true);
What am I doing wrong?
It turns out that the missing piece was simulating an ALT click (just the up part part is sufficient) before calling SetForegroundWindow(). No need to call SwitchToThisWindow().
As a bonus, setting ActiveExplorer().CurrentFolder() = ... reliably scrolls up & down to the selected folder (which it wasn't doing when outlook was not in the foreground).