Centering a WPF Window in an Outlook 2013 Add-in

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!

 


Posted

in

by

Tags:

Comments

One response to “Centering a WPF Window in an Outlook 2013 Add-in”

  1. CoRe23 Avatar
    CoRe23

    Thank you very much, i was seraching this for a week, working with VSTO c# plugin using WPF

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: