How to capture the event of a form being moved (and how to prevent a form being moved off screen)
Delphi does not expose an OnMoving event handler for forms, which would otherwise notify you that a form is being moved by the user. The event associated with a form being moved can be captured in code and acted upon.
To capture the OnMoving event, add an event handler to respond to the
WM_MOVING message. Do this by adding the following to the definition of
procedure OnMoving(var Msg: TWMMoving); message WM_MOVING;
My Delphi system did not come with a definition of the
so you may need to add the following definition:
TWMMoving = record Msg: Cardinal; fwSide: Cardinal; lpRect: PRect; Result: Integer; end;
In your event handler
msg.lpRect^.Left holds the new Left
coordinate of the form and
msg.lpRect^.Top holds the new Top
coordinate of the form.
In your OnMove event handler be sure to allow the base class (TForm)
to process the message by calling
To illustrate a typical example of how this could be used, the following function ensures that the form cannot be moved off the screen:
procedure TWebPublisher.OnFormMoving(var Msg: TWMMoving);
screenArea := Screen.WorkareaRect;
if msg.lprect^.Left < screenArea.left then
OffsetRect(msg.lprect^, screenArea.Left - msg.lpRect^.Left, 0);
if msg.lprect^.Top < screenArea.top then
OffsetRect(msg.lprect^, 0, screenArea.Top - msg.lprect^.Top);
if msg.lprect^.Right > screenArea.Right then
OffsetRect(msg.lprect^, screenArea.right - msg.lprect^.Right, 0);
if msg.lprect^.Bottom > screenArea.Bottom then
OffsetRect(msg.lprect^, 0, screenArea.bottom - msg.lprect^.Bottom);
These notes are believed to be correct for Delphi 6 and may apply to other versions as well.
About the author: Brian Cryer is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.