Marcel B
Marcel B

Reputation: 3674

How to center a WPF app on screen?

I want to center my WPF app on startup on the primary screen. I know I have to set myWindow.Left and myWindow.Top, but where do I get the values?

I found System.Windows.Forms.Screen.PrimaryScreen, which is apparently not WPF. Is there a WPF alternative that gives me the screen resolution or something like that?

Upvotes: 134

Views: 144653

Answers (9)

You have property in window WindowStartupLocation.

Choose CenterScreen.

Please refer to the below image for more info. enter image description here

Upvotes: -1

Pratik Deoghare
Pratik Deoghare

Reputation: 37192

xaml

<Window ... WindowStartupLocation="CenterScreen">...

Upvotes: 203

Jason Robinson
Jason Robinson

Reputation: 31

I prefer to put it in the WPF code.

In [WindowName].xaml file:

<Window x:Class=...
...
WindowStartupLocation ="CenterScreen">

Upvotes: 3

Artem
Artem

Reputation: 145

var window = new MyWindow();

for center of the screen use:

window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

for center of the parent window use:

window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;

Upvotes: 4

Mehdi
Mehdi

Reputation: 2283

You don't need to reference the System.Windows.Forms assembly from your application. Instead, you can use System.Windows.SystemParameters.WorkArea. This is equivalent to the System.Windows.Forms.Screen.PrimaryScreen.WorkingArea!

Upvotes: 8

Indy9000
Indy9000

Reputation: 8881

Put this in your window constructor

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

.NET FrameworkSupported in: 4, 3.5, 3.0

.NET Framework Client ProfileSupported in: 4, 3.5 SP1

Upvotes: 169

Eddie Butt
Eddie Butt

Reputation: 503

What about the SystemParameters class in PresentationFramework? It has a WorkArea property that seems to be what you are looking for.

But, why won't setting the Window.WindowStartupLocation work? CenterScreen is one of the enum values. Do you have to tweak the centering?

Upvotes: 8

Michael Petrotta
Michael Petrotta

Reputation: 60962

You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):

Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;

...works just fine.

Have you considered setting your main window property WindowStartupLocation to CenterScreen?

Upvotes: 49

Jeff Yates
Jeff Yates

Reputation: 62397

There is no WPF equivalent. System.Windows.Forms.Screen is still part of the .NET framework and can be used from WPF though.

See this question for more details, but you can use the calls relating to screens by using the WindowInteropHelper class to wrap your WPF control.

Upvotes: 2

Related Questions