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:
(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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With