65.9K
CodeProject is changing. Read more.
Home

Very simple way to restore form window to its previous state

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Mar 16, 2011

CPOL
viewsIcon

10590

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: MainWindowStateType:...

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.