Save Forms’ Size and Location at Run Time

You’ve noticed how some apps display forms and toolboxes in the same location and size as when you last closed them. Here’s some simple code that gives your VB app the same effect by using the Registry. First, fill in an appropriate Tag property for your form at design time?something like Main Application Form or Color Tool Box. Then keep a global string constant called ApplicationName that holds the title for your application. It’s used here to distinguish the Registry key, but it can also be used for error messages. Place this line in a module:

 Public Const ApplicationName = "My Application Name"

Finally, place this code in a module:

 Public Sub SaveFormDisplaySettings(frm As Form)	If frm.Tag = "" Then Exit Sub	SaveSetting ApplicationName, frm.Tag & _		" Display Settings", "Top", Str(frm.Top)	SaveSetting ApplicationName, frm.Tag & _		" Display Settings", "Left", Str(frm.Left)	SaveSetting ApplicationName, frm.Tag & _		" Display Settings", "Height", Str(frm.Height)	SaveSetting ApplicationName, frm.Tag & _		" Display Settings", "Width", Str(frm.Width)End SubPublic Sub LoadFormDisplaySettings(frm As Form)	Dim FormSettings As Variant	Dim intSettings As Integer	If frm.Tag = "" Then Exit Sub	FormSettings = GetAllSettings(ApplicationName, frm.Tag & _		" Display Settings")	If IsEmpty(FormSettings) Then Exit Sub	For intSettings = LBound(FormSettings, 1) _		To UBound(FormSettings, 1)	Select Case FormSettings(intSettings, 0)		Case "Left"			frm.Left = Val(FormSettings(intSettings, 1))		Case "Top"			frm.Top = Val(FormSettings(intSettings, 1))		Case "Height"			frm.Height = Val(FormSettings(intSettings, 1))		Case "Width"			frm.Width = Val(FormSettings(intSettings, 1))	End Select	Next intSettingsEnd Sub

Add this line to the Form_Load events of the forms you want to save:

 Call LoadFormDisplaySettings(Me)

Add this line to the Form_Unload events:

 Call SaveFormDisplaySettings(Me)

Note one side effect: These Registry settings remain in the Registry even after the application has been uninstalled. They’re stored at or below HKEY_CURRENT_USERSoftwareVB and VBA Program SettingsMy Application Name.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: