I recently came upon the need to show a WPF window in an Outlook add-in, preferably centered on the Outlook window (WindowStartupLocation = CenterInParent). Easy enough, but without setting Window.Owner, it will appear in an uncontrolled location when calling ShowDialog().
Setting Window.Owner is where things get a little tricky.
Searching online produced a few variations of the theme of using the WindowInteropHelper class in combination with the win32 FindWindow API with the window caption discovered via Reflection. Yuck. Surely there’s a better way.
Enter System.Process. One of the properties of the System.Process class is MainWindowHandle, which Microsoft states:
The main window is the window opened by the process that currently has the focus (the TopLevel form).
Sounds like exactly what I’m looking for. A quick call to Process.GetCurrentProcess() and we’ve got everything we need. The final code to show the WPF window is:
SomeView view = new SomeView(); WindowInteropHelper helper = new WindowInteropHelper(view); helper.Owner = Process.GetCurrentProcess().MainWindowHandle; view.ShowDialog();
Simple as that!
Leave a Reply