Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you center your main window in WPF?

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.

like image 432
paxdiablo Avatar asked Oct 26 '10 00:10

paxdiablo


1 Answers

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.

like image 116
Reed Copsey Avatar answered Sep 21 '22 22:09

Reed Copsey