Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Very simple way to restore form window to its previous state

By , 20 Mar 2011
Rate this:
Please Sign up or sign in to vote.
Here is a way to do this without using the registry.
In the project's properties, Settings pane, add the following settings. You can name these settings anything you want, but use the same setting name in the code shown below:
Name: MainWindowState
Type: System.Windows.Forms.FormWindowState
Scope: User
-----
Name: MainWindowLocation
Type: System.Drawing.Point
Scope: User
-----
Name: MainWindowSize
Type: System.Drawing.Size
Scope: User
Put the following in the form's Load event:
Try
    Dim st As FormWindowState = My.Settings.MainWindowState
    Dim siz As Size = My.Settings.MainWindowSize
    Dim loc As Point = My.Settings.MainWindowLocation
    Me.WindowState = st
    If Me.WindowState = FormWindowState.Normal Then
        If siz.Width <> 0 AndAlso siz.Height <> 0 Then Me.Size = siz
        If loc.X <> 0 AndAlso loc.Y <> 0 Then Me.Location = loc
    End If
 
Catch ex As Exception
    Me.Location = New Point(100, 100)
End Try
Put the following in the form's FormClosing event:
My.Settings.MainWindowState = Me.WindowState
If Me.WindowState = FormWindowState.Normal Then
    My.Settings.MainWindowLocation = Me.Location
    My.Settings.MainWindowSize = Me.Size
End If
My.Settings.Save()
Add settings for as many forms as you want to track in your project, and adjust the code accordingly. Put the code blocks in each form, referencing the proper setting name. Each user will then have the forms appear exactly as he/she left them the last time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

RMittelman
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
Generalnice answer I prefer to steer away from the registry as much... PinmemberSimon_Whale6-Jun-11 1:34 
GeneralYou could also use Xml file to accomplish this Pinmembercharles henington20-Mar-11 20:46 
GeneralI prefer the settings method as well. This allows for bette... PinmemberTheyCallMeMrJames20-Mar-11 11:30 
I prefer the settings method as well. This allows for better portability and is more in line with recent guidance.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 20 Mar 2011
Article Copyright 2011 by RMittelman
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid