|
|
Title | Shrink a form to a title bar and restore it when the user clicks on the caption |
Keywords | form, shrink, restore, minimize |
Categories | Tips and Tricks, API |
|
|
When the user clicks the Shrink button, shrink the form to the smallest possible size.
When the form resizes, save its new size.
Subclass the form. When you see a WM_NCLBUTTONDOWN message, see if the click is on the caption area. If it is, restore the most recently saved size.
|
|
' Process messages.
Public Function NewWindowProc(ByVal hwnd As Long, ByVal msg _
As Long, ByVal wParam As Long, ByVal lParam As Long) As _
Long
Const WM_NCDESTROY = &H82
Const HTCAPTION = 2
Const WM_NCLBUTTONDOWN = &HA1
' If we're being destroyed,
' restore the original WindowProc.
If msg = WM_NCDESTROY Then
SetWindowLong _
hwnd, GWL_WNDPROC, _
OldWindowProc
End If
' See if this is WM_NCLBUTTONDOWN.
If msg = WM_NCLBUTTONDOWN Then
' This is WM_NCLBUTTONDOWN. See if we
' clicked in the caption area.
If wParam = HTCAPTION Then
' This is in the caption area.
' Restore the form.
Form1.Restore
End If
End If
' Call the original WindowProc.
NewWindowProc = CallWindowProc( _
OldWindowProc, hwnd, msg, wParam, _
lParam)
End Function
|
|
The following code shows how the form tracks its size. The Form_Load event handler uses the GetSystemMetrics API function to find the minimum height and width that a form can have. It then subclasses the form.
The most important part of Form_Resize is where it saves the form's new width and height so the program can restore the form.
The cmdShrink_Click event handler makes the form as small as possible.
Subroutine Restore gives the form its last recorded size.
|
|
Private Sub Form_Load()
' Get the minimum window size.
m_MinWidth = ScaleX(GetSystemMetrics(SM_CXMIN), _
vbPixels, vbTwips)
m_MinHeight = ScaleY(GetSystemMetrics(SM_CYMIN), _
vbPixels, vbTwips)
' Subclass the form.
OldWindowProc = SetWindowLong( _
hwnd, GWL_WNDPROC, _
AddressOf NewWindowProc)
End Sub
Private Sub Form_Resize()
' Move the Shrink button to the lower left corner.
cmdShrink.Move _
ScaleWidth - cmdShrink.Width, _
ScaleHeight - cmdShrink.Height
' Do nothing more if we are minimized or maximized.
If WindowState = vbMinimized Or _
WindowState = vbMaximized Then Exit Sub
' Do nothing if we are shrinking.
If m_Shrinking Then Exit Sub
' Do nothing if we are restoring from being
' minimized.
If Width <= m_MinWidth Then Exit Sub
If Height <= m_MinHeight Then Exit Sub
' Save the new height and width.
OrigWidth = Width
OrigHeight = Height
End Sub
Private Sub cmdShrink_Click()
' Make sure we are not minimized or maximized.
If WindowState <> vbNormal Then WindowState = vbNormal
' Set m_Shrinking = True so Form_Resize
' doesn't save the shrunk size.
m_Shrinking = True
Move Left, Top, m_MinWidth, m_MinHeight
m_Shrinking = False
End Sub
Public Sub Restore()
Move Left, Top, OrigWidth, OrigHeight
End Sub
|
|
For more information on subclassing including important precautions, see Tutorial: Subclassing.
|
|
|
|
|
|