Keep a Window Visible
Prevent users from moving windows offscreen.
by Karl E. Peterson
Technology Toolbox: VB6, VB5
Q: Keep Your Window
How can I prevent a user from moving a window off the screen? I'd like to allow users to move a window around the desktop at will, but not allow them to move any part of the window off the desktop. The entire window must be viewable at all times.
Windows sends WM_MOVING messages to a window immediately prior to the user getting any feedback. These messages are accompanied by a pointer to a RECT structure in lParam that contains the drag rectangle coordinates Windows displays to the user. You're only given a pointer, so you need to copy the data at this address to a RECT structure declared within your hook procedure (see Listing 1).
At this point, you're free to examine the RECT coordinates and even modify them to suit your needs. In this case, you'd want to ensure that none of the edges go past the edge of the screen, and if they do, correct them to remain onscreen. After any necessary modifications, copy the updated structure back to the same address passed in lParam and tell Windows you've handled the message by returning True for the function result. —K.E.P.
About the Author