In Visual Basic, the main task of preserving the form state (size, position, field values) between sessions involves writing data to an external source (file, registry, user settings) upon closing and restoring it upon startup.
Approaches:
Example of using My.Settings:
' Saving state Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing My.Settings.WindowLocation = Me.Location My.Settings.WindowSize = Me.Size My.Settings.Save() End Sub ' Restoring state Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load If Not My.Settings.WindowSize.IsEmpty Then Me.Size = My.Settings.WindowSize End If If Not My.Settings.WindowLocation.IsEmpty Then Me.Location = My.Settings.WindowLocation End If End Sub
Settings are added through the designer or manually.
Nuances:
Can you save a non-standard object (for example, DataTable) through My.Settings? How should this be correctly implemented?
Answer: Yes, but the setting must be of type User, and the object must support serialization. For DataTable or complex objects, My.Settings saves the serialized Binary/XML format. You need to implement serialization support or use manual writing via the serializer.
Story
In the application, the state of the form was saved in the Windows Registry. After some updates, users lost access to settings due to permission restrictions, which led to a surge in support requests. The solution was to switch to My.Settings in user profiles.
Story
Without checking the coordinates of the window's position at startup, the application displayed outside the visible area of the screen (the second monitor was changed). Logic for checking the desktop boundaries has now been added when restoring the form's position.
Story
When updating from an old version of the application, developers failed to ensure the transfer of user settings (nested fields of forms). The result was data loss and user dissatisfaction. A policy for supporting version migration with compatibility control has been adopted.