Pradeep Singh
Pradeep Singh

Reputation: 243

Saving the forms desktop location and size

I am using winforms and I want to save the desktop location and size of the form when the user changes either. I found some useful code and put that in the form closing event and form load event to save and load the size and location respectively.

However, when the user directly shuts down the PC without closing the program first the changed size and location is not saved.

Therefore I used the same code in the size changed and location changed events but it does not work and size and location are not changed when the program restarts.

private void frmScopeStatus_SizeChanged(object sender, EventArgs e)
{
    Application.UserAppDataRegistry.SetValue("WindowState", this.WindowState);
    Application.UserAppDataRegistry.SetValue("WindowSizeH", this.Size.Height);
    Application.UserAppDataRegistry.SetValue("WindowSizeW", this.Size.Width);
    Application.UserAppDataRegistry.SetValue("LocationX", this.DesktopLocation.X);
    Application.UserAppDataRegistry.SetValue("LocationY", this.DesktopLocation.Y);
}

 private void frmScopeStatus_LocationChanged(object sender, EventArgs e)
{
    Application.UserAppDataRegistry.SetValue("WindowState", this.WindowState);
    Application.UserAppDataRegistry.SetValue("WindowSizeH", this.Size.Height);
    Application.UserAppDataRegistry.SetValue("WindowSizeW", this.Size.Width);
    Application.UserAppDataRegistry.SetValue("LocationX", this.DesktopLocation.X);
    Application.UserAppDataRegistry.SetValue("LocationY", this.DesktopLocation.Y);
}

Upvotes: 0

Views: 931

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You can provide Application Settings data bindings of User scope to store these values.

  • Open your form in designer
  • Go to form properties Data > (Application Settins) group
  • Add databining for Location (and ClientSize) property (scope User)
  • On FormClosing event save changed properties Properties.Settings.Default.Save();

This will create for each user of your application file (at %SYSTEMDRIVE%/Users/{username}/AppData/Local/CompanyName/AppName) with user settings, which will be applied when application starts:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <AppName.Properties.Settings>
            <setting name="FormLocation" serializeAs="String">
                <value>345, 234</value>
            </setting>
            <setting name="FormSize" serializeAs="String">
                <value>458, 555</value>
            </setting>
        </AppName.Properties.Settings>
    </userSettings>
</configuration>

BTW I think FormClosed event is better for saving application settings.

Upvotes: 3

Related Questions