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
 
 
 
 
 
TitlePrevent a form from moving
DescriptionThis example shows how to prevent a form from moving in Visual Basic 6. The program subclasses and restores the form's position when it sees a WINDOWPOSCHANGING message.
Keywordsno move, prevent move
CategoriesControls, Tips and Tricks, API
 
The easy way to prevent a VB 6 form from moving is to set its Moveable property to False. Thanks to Martijn Coppoolse for pointing that out. In earlier versions of Visual Basic, you can use subclassing.

When the program starts, it saves its position and then subclasses the form.

Warning: Subclassing is dangerous. The debugger does not work well when a new WindowProc is installed. If you halt the program instead of unloading its forms, it will crash and so will the Visual Basic IDE. Save your work often! Don't say you weren't warned.

 
Private Sub Form_Load()
    ' Set the border so the user cannot resize the form.
    BorderStyle = vbFixedDialog

    ' Get the desired location in pixels.
    DesiredX = ScaleX((Screen.Width - Width) / 2, vbTwips, _
        vbPixels)
    DesiredY = ScaleY((Screen.Height - Height) / 2, _
        vbTwips, vbPixels)

    ' Install the new WindowProc.
    OldWindowProc = SetWindowLong( _
        hwnd, GWL_WNDPROC, _
        AddressOf NewWindowProc)

    ' Move the window to its desired location the first
    ' time.
    Left = (Screen.Width - Width) / 2
    Top = (Screen.Height - Height) / 2
End Sub
 
The new WindowProc watches for the WM_NCDESTROY message and restores the original WindowProc when the form is closing. When it sees the WM_WINDOWPOSCHANGING message, it resets the form's location.
 
' Process messages.
Public Function NewWindowProc(ByVal hwnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, lParam As WINDOWPOS) As _
    Long
Const WM_NCDESTROY = &H82
Dim new_aspect As Single

    ' If we're being destroyed,
    ' restore the original WindowProc.
    If msg = WM_NCDESTROY Then
        SetWindowLong _
            hwnd, GWL_WNDPROC, _
            OldWindowProc
    End If

    ' Keep the aspect ratio.
    If msg = WM_WINDOWPOSCHANGING Then
        ' Reset the position.
        lParam.x = DesiredX
        lParam.y = DesiredY
    End If

    ' Continue normal processing. VERY IMPORTANT!
    NewWindowProc = CallWindowProc( _
        OldWindowProc, hwnd, msg, wParam, _
        lParam)
End Function
 
Note that the user can still resize the form.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated