Saving and Restoring a Form's Window Position

By Jonathan Wood on 9/21/2014
Language: C#
Technology: .NETWinForms
Platform: Windows
License: CPOL
Views: 5,150
Frameworks & Libraries » WinForms » General » Saving and Restoring a Form's Window Position


When a user runs your application, it can be extremely helpful if your application can restore settings to the same value they were the last time the application was run. This prevents the user from having to re-select those settings every time they run your application.

There are many types of settings that are candidates for being saved this way. One setting that is perhaps not as important, but still helpful, is to save the current window position.

This setting is less important because window positions normally change all the time, and they are very easy to set. Still, if the user likes your application's main window in a particular state or position, it is nice to have that position restored each time the user runs that application.

In this article, I will present two routines for saving and then restoring the position of your application's main window in a WinForms application.

Things to Consider

This is not at all a complex task; however, there are some things to consider. First, you need to take into account both the window position and the window state (minimized, maximized, or normal).

If the window is maximized, for example, you should not store only the window's position. A maximized window is not the same as one in the normal state that is sized to fill the screen. Also, it's possible that the screen is a different resolution or size than the last time the application ran. Obviously, a maximized window should fill the screen no matter what the screen size or resolution. So you need to save and restore the window state, in addition to the window position.

Furthermore, if the window is restored to a maximized state and then the user changes the window to a non-maximized (normal) state, the window should ideally revert to any normal position used the last time the application was run.

Finally, the code should be robust enough to where the program doesn't crash if any unexpected conditions are encountered.

The code I will present in this article will attempt to address all of these considerations.

Presenting the Code

Listing 1 shows my SaveWindowPosition() and RestoreWindowPosition() methods. Because the code is so short, I am not including any demo projects for download. You can simply place these two methods in the code for one of your WinForms.

Note that these routines save and restore the window position in a single string. This makes it easy to store that string anyplace you want your settings stored. In my case, I'm storing it in the Windows registry. But the code could easily be modified to save the window position in your application settings, or other location.

Normally, this code would be used in your application's main form, but the technique could be applied to multiple forms in the same application. However, you'll need to use unique setting names to distinguish between the different forms so that not all forms used the same settings.

IMPORTANT: If you use the code below as is, you should at least change the registry settings (RegistrySettings.CompanyName, RegistrySettings.ApplicationName, and RegistrySettings.SettingType) so that each application will use it's own window-position settings, and you don't have one application loading the window position that was saved by another application.

Listing 1: The SaveWindowPosition() and RestoreWindowPosition() Methods

private void SaveWindowPosition()
    Rectangle rect = (WindowState == FormWindowState.Normal) ? DesktopBounds : RestoreBounds;
    RegistrySettings.SetSetting("WindowPosition", String.Format("{0},{1},{2},{3},{4}",
        rect.Left, rect.Top, rect.Width, rect.Height));

private void RestoreWindowPosition()
        string s = RegistrySettings.GetSetting("WindowPosition") as string;
        if (s != null)
            List<int> settings = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                  .Select(v => int.Parse(v)).ToList();
            if (settings.Count == 5)
                this.SetBounds(settings[1], settings[2], settings[3], settings[4]);
                this.WindowState = (FormWindowState)settings[0];
    catch { /* Just leave current position if error */ }

The SaveWindowPosition() method simply constructs a string based on the current window position and state. If the window is in a normal state, then the rectangle stored is based on DesktopBounds, which describes the current position of the window on the desktop.

But if the window is minimized or maximized, then the rectangle stored is based on RestoreBounds. RestoreBounds describes the position of the window if the user restores a minimized or maximized window. By saving this value, the code remembers the window's normallized position even if the window is currently minimized or maximized.

The window state is an enum, but it is converted to an integer for simplicity.

The RestoreWindowPosition() method requires a little more code. It starts by reading the string back from the registry and parsing the string into a List of integer values. The code then uses those values to set the form's window position. Finally, the code sets the window state.

If the form is being restored to a minimized or maximum state, this code first sets the normal window position and then minimizes or maximizes the form. So if the user changes a minimized or maximized window to the normal state, the window will be positioned in the normal state from the last application session.

Note that there is some basic error checking here, but since a user could go in and edit the registry settings to be anything, the code is wrapped in a try...catch block to catch any unexpected exceptions. Any exceptions are simply ignored. If there is something funky going on, then the window simply won't get restored, which isn't the end of the World.


That's it: Just two very simple methods to perform this task.

One possible change to consider to my code is when you save the position of a form that is in the minimized state. Normally, a user starting an application will not want it to start out minimized. So it would be easy to have the code check if the window is minimized, and restore to the normal state instead.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.

I hike each week with my dogs Suki and Sasha. You can see my hiking blog at Hiking Salt Lake.