Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving WPF WIndow and Position

Tags:

windows

wpf

What would be the best way to save the window position and size in a WPF app?

Currently, I'm saving the window size and position of a WPF App. Here are the events I handle:

  1. SourceInitialized : The saved info is loaded on to the window
  2. WindowClosing : The current info is saved to the backing store

(I copied this from an example).

The problem is, when the window is minimized and restored, the settings from the last WindowClosing is retrieved.

Now, the StateChanged event fire AFTER the window has minimized, so it does not seem to be what i need.

Thanks

like image 780
moogs Avatar asked Apr 13 '26 17:04

moogs


2 Answers

Do yourself and your users a favor and use the LocationChanged event and the SizeChanged event to save the settings at that time. There's nothing more annoying than an application that gets amnesia if the process exits abnormally and settings don't get saved (cough...explorer...cough...)

Then just check to make sure the WindowState == Normal before saving the settings. Obviously its pointless to save the position of a minimized or maximized window.

As for when to load the settings, well that you can just do in the constructor after the InitializeComponent call or you can use the Initialized event. No real reason to use the SourceInitialized event unless you are doing something with the HWND directly which shouldn't be necessary.

like image 141
Josh Avatar answered Apr 16 '26 12:04

Josh


Use the WindowInteropHelper object to get the window handle and use Screen.FromHandle method to get the actual screen the window is on. When saving make sure to also save the screen bounds just in case it does not exist any more.

One caveat when restoring the screen to its former state is it has to be done after the window handle is created so can't do it in the constructor else won't work properly in multiple monitor situations. Try doing it on the SourceInitialized callback

like image 30
outro56 Avatar answered Apr 16 '26 13:04

outro56



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!