Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleMake a form keep the same aspect ratio when it resizes
Keywordsform, aspect ratio, size, resize
CategoriesTips and Tricks, API
 
Subclass. In WM_WINDOWPOSCHANGING messages, adjust the width and height as necessary to keep the aspect ratio.
 
Private Sub Form_Load()
    OldWindowProc = SetWindowLong( _
        hwnd, GWL_WNDPROC, _
        AddressOf NewWindowProc)
End Sub

Public Function NewWindowProc(ByVal hwnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, lParam As WINDOWPOS) As _
    Long
Static done_before As Boolean
Static aspect As Single
Dim new_aspect As Single

    ' Keep the aspect ratio.
    If msg = WM_WINDOWPOSCHANGING Then
        If lParam.cy > 0 Then
            ' Save the aspect ratio the first.
            If Not done_before Then
                aspect = lParam.cx / lParam.cy
                done_before = True
            End If
            
            new_aspect = lParam.cx / lParam.cy
            If new_aspect > aspect Then
                ' Too short/wide. Make it taller.
                lParam.cy = lParam.cx / aspect
            Else
                ' Too tall/thin. Make it wider.
                lParam.cx = aspect * lParam.cy
            End If
        End If
    End If

    ' Continue normal processing. VERY IMPORTANT!
    NewWindowProc = CallWindowProc( _
        OldWindowProc, hwnd, msg, wParam, _
        lParam)
End Function
 
Formatted by Neil Crosby
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated