Option Explicit
Private Const APP_NAME = "LastPos"
Private Const SECTION_NAME = "Geometry"
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type WINDOWPLACEMENT
Length As Long
flags As Long
showCmd As Long
ptMinPosition As POINTAPI
ptMaxPosition As POINTAPI
rcNormalPosition As RECT
End Type
Private Declare Function GetWindowPlacement Lib "user32" (ByVal hWnd As Long, lpwndpl As WINDOWPLACEMENT) As Long
' Load the form's geometry from the registry.
Private Sub Form_Load()
Dim l As Single
Dim t As Single
Dim w As Single
Dim h As Single
' Load the form's last dimensions
' from the registry.
w = CSng(GetSetting(APP_NAME, SECTION_NAME, _
"Width", Format$(Width)))
h = CSng(GetSetting(APP_NAME, SECTION_NAME, _
"Height", Format$(Height)))
l = CSng(GetSetting(APP_NAME, SECTION_NAME, _
"Left", Format$(Left)))
t = CSng(GetSetting(APP_NAME, SECTION_NAME, _
"Top", Format$(Top)))
Move l, t, w, h
' Restore the window state.
WindowState = CInt(GetSetting(APP_NAME, SECTION_NAME, _
"WindowState", Format$(vbNormal)))
End Sub
' Save the form's geometry in the registry.
Private Sub Form_Unload(Cancel As Integer)
Dim wp As WINDOWPLACEMENT
Dim left_value As Single
Dim top_value As Single
Dim width_value As Single
Dim height_value As Single
' Do nothing if the form is not visible.
If Visible = False Then Exit Sub
' Get the window's normalized placement.
wp.Length = Len(wp)
GetWindowPlacement hWnd, wp
' Convert the values from pixels into twips.
left_value = wp.rcNormalPosition.Left * Screen.TwipsPerPixelX
top_value = wp.rcNormalPosition.Top * Screen.TwipsPerPixelX
width_value = (wp.rcNormalPosition.Right - wp.rcNormalPosition.Left) * Screen.TwipsPerPixelY
height_value = (wp.rcNormalPosition.Bottom - wp.rcNormalPosition.Top) * Screen.TwipsPerPixelY
' Save the dimensions.
SaveSetting APP_NAME, SECTION_NAME, _
"Left", Format$(left_value)
SaveSetting APP_NAME, SECTION_NAME, _
"Top", Format$(top_value)
SaveSetting APP_NAME, SECTION_NAME, _
"Width", Format$(width_value)
SaveSetting APP_NAME, SECTION_NAME, _
"Height", Format$(height_value)
' Save the window state.
SaveSetting APP_NAME, SECTION_NAME, _
"WindowState", Format$(WindowState)
End Sub