views:

58

answers:

4

I have a WPF application and I need to know how to center the wain window programatically (not in XAML).

I need to be able to do this both at startup and in response to certain user events. It has to be dynamically calculated since the window size itself is dynamic.

What's the simplest way to do this? Under old Win32 code, I'd call the system metrics functions and work it all out. Is that still the way it's done or is there a simple CenterWindowOnScreen() function I can now call.

A: 

As a basic solution, you can use the window's StartupLocation property, set it to one of the enum values defined in System.Windows.WindowStartupLocation enumeration, there is one for center of screen:

_wpfWindow.StartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

Unfortunately it's not always quite so simple; you need to account for multiple monitors, taskbars, etc. The "CenterScreen" option opens the window in the center of the screen that has the mouse cursor. See this SO question for a lot of information, or reference the api.

Guy Starbuck
+5  A: 

Well, for startup time, you can set the startup location:

window.WindowStartupLocation = WindowStartupLocation.CenterScreen;

Later, you'll need to query it. The information (at least for the primary screen) is available via SystemParameters.PrimaryScreenWidth/Height.

Reed Copsey
A: 

There's no automatic function that I know of, but you can work it out from what you get in SystemParameters.WorkArea.

500 - Internal Server Error
+1  A: 
private void CenterWindowOnScreen()
    {
        double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
        double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
        double windowWidth = this.Width;
        double windowHeight = this.Height;
        this.Left = (screenWidth / 2) - (windowWidth / 2);
        this.Top = (screenHeight / 2) - (windowHeight / 2);
    }

You can use this method to set the window position to the center of your screen.

Noppol Pilukruangdet
I'll give you one for that but I seem to recall it's a lot more work, taking into account task bars and so forth. Still, +1 for the `SystemParameters` and some code so I don't have to go out to `GetSystemMetrics` myself.
paxdiablo