Many posts around about restoring a WinForm position and size.
Examples:
- http://www.stackoverflow.com/questions/92540/save-and-restore-form-position-and-size
- http://www.codeproject.com/KB/dialog/restoreposition.aspx?fid=1249382&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2595746
But I have yet to find code to do this with multiple monitors.
That is, if I close my .NET Winform app with the window on monitor 2, I want it to save the windows size, location, and state to the application settings, so it could later restore to monitor 2 when I restart the app. It would be nice if, like in the codeproject example above, it includes some sanity checks, as in if the saved location is mostly off-screen it “fixes” it. Or if the saved location is on a monitor that is no longer there (e.g. my laptop is now by itself without my second monitor) then it correctly moves it to monitor 1.
Any thoughts?
My environment: C#, .NET 3.5 or below, VS2008
The answer provided by VVS was a great help! I found two minor issues with it though, so I am reposting the bulk of his code with these revisions:
(1) The very first time the application runs, the form is opened in a Normal state but is sized such that it appears as just a title bar. I added a conditional in the constructor to fix this.
(2) If the application is closed while minimized or maximized the code in OnClosing fails to remember the dimensions of the window in its Normal state. (The 3 lines of code–which I have now commented out–seems reasonable but for some reason just does not work.) Fortunately I had previously solved this problem and have included that code in a new region at the end of the code to track window state as it happens rather than wait for closing.
With these two fixes in place, I have tested:
A. closing in normal state–restores to same size/position and state
B. closing in minimized state–restores to normal state with last normal size/position
C. closing in maximized state–restores to maximized state and remembers its last size/position when one later adjusts to normal state.
D. closing on monitor 2–restores to monitor 2.
E. closing on monitor 2 then disconnecting monitor 2–restores to same position on monitor 1
David: your code allowed me to achieve points D and E almost effortlessly–not only did you provide a solution for my question, you provided it in a complete program so I had it up and running almost within seconds of pasting it into Visual Studio. So a big thank you for that!