I have 2 monitors and I need to save form position and it should show on screen where it was closed.
Can someone suggest how to get screen on which it is, and on form load show it on screen where form was closed?
The settings I save in registry.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The simplest way is to call the
GetWindowPlacementfunction. That returns aWINDOWPLACEMENTstructure that contains information about the window’s on-screen coordinates.Using this function instead of the
Form.Locationproperty solves the problems you’ll experience with multiple monitors, minimized windows, strangely positioned taskbars, etc.The route of attack would be to call the
GetWindowPlacementfunction when your application is shutting down, persist the location of the window to the registry (or wherever you are storing it—the registry is no longer the recommended place for saving application state), and then when your application is re-opened, calling the correspondingSetWindowPlacementfunction to restore the window to its previous position.Since these are native functions exposed by the Win32 API, and you’re working in C#, you’ll need to call them via P/Invoke. Here are the required definitions (for organizational purposes, I recommend placing these in a static class named
NativeMethods):To get the current position of your window (which you would do when your app is closing), use this code:
Recall that I mentioned the registry is no longer the recommended place for persisting application state. Since you’re developing in .NET, you have much more powerful and versatile options available. And since the
WINDOWPLACEMENTclass declared above is marked[Serializable], it would be very easy to serialize this information to your application settings, and then reload it the next time you open.