Skip to content

Windows.Forms Settings : Auto Save state (size and position) of all my Forms

We will cover three topics in one

  • Using a single settings variable to save ever forms window state
  • Base class inheritance in winforms
  • Data contracts and JSON

In a nutshell, we will serialise and deserialise into a strongly typed custom settings class to and from JSON to store out our windows forms window states, in a settings variable in the project, using a custom settings class that is present in a baseClass that every form within your project will inherit from

What are data contracts

A data contract is essentially a simple way of serialising a class into a string for storage and/or transport

In simple terms, when you mark a class as a data contract you are telling .NET that this class will have properties that can be stored as a string (in our case serialised to JSON).

this is how to mark a class as a data contract

And members that you would like to store in your JSON should be marked as data members like so

How do data contracts work with JSON?

A long time ago I wrote a generic serialiser/deserialiser to convert datacontract classes to and from JSON, this is the code

we are going to reference these function later in this article

How do we use inheritance in winforms

Windows forms classes that you are exposed to are essentially partial classes. If you have a project open that contains a Windows.Forms.Form, then unhide all documents and take a look at the difference between the code behind the form that you see and the designer generated code. The file names will have this structure

  • frmName.vb
  • frmName.designer.vb

Partial classes are a really nice way to extend the reach of a single class, but separate the code file

So, create a baseclass ready to be inherited by all of your windows forms

  • frmName.vb
  • frmName.designer.vb
  • BaseForm.vb

create the project settings property

next we create our custom project settings property “FormSizesAndLocations”


The custom settings class

we need our settings class to be able to do the following

  • read the settings from the config
  • save a forms window state to the config
  • name, width, height, x position, y position, maximised, minimised

here is our custom settings class for saving window state and reading window state, note the data contract attribute and the data member attributes to those properties we want to persist

The BasePage class that will do all the work

Now lets create a base page class, in this class we will put the logic to handle the position save and load of any form that then inherits this class

Rather than describe the code, you should really be able to understand it, so lets dive into the forms base class

And there you have it

Posted in .NET, Development, optimisation, VB.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.