Title: Prevent a Delphi Form from Being Moved Off Screen
As the most important building block of any Delphi application, the TForm object is most of the times used as is.
Delphi's TForm object provides enough properties and events to help you do (and control) whatever needed with it.
Sometimes you'll find out that a few events or properties are missing...
Try creating a simple form application. Now move the form outside of the screen area. You can easily do this by simply dragging the form by its caption (title) area to the right - not that the part of the form to the right of the mouse pointer can easily be moved outside of the work area of the screen!
Do not go off screen!
What if you do not want the form of your Delphi application to be moved of the screen?
There's no OnMoving event you can handle. Luckily, using Delphi it is easy to add one:
To handle the OnMoving event add the following to the definition of your form (private section):
procedure WMMoving(var Msg: TWMMoving); message WM_MOVING;
The WM_MOVING message is sent to a window that the user is moving. By processing this message, an application can monitor the size and position of the drag rectangle and, if needed, change its size or position.
Write the code to reposition the form if the user is trying to move it off the screen:
procedure TPopupForm.WMMoving(var Msg: TWMMoving) ;
var
workArea: TRect;
begin
workArea := Screen.WorkareaRect;
with Msg.DragRect^ do
begin
if Left then
OffsetRect(Msg.DragRect^, workArea.Left - Left, 0) ;
if Top then
OffsetRect(Msg.DragRect^, 0, workArea.Top - Top) ;
if Right workArea.Right then
OffsetRect(Msg.DragRect^, workArea.Right - Right, 0) ;
if Bottom workArea.Bottom then
OffsetRect(Msg.DragRect^, 0, workArea.Bottom - Bottom) ;
end;
inherited;
end;
The above WM_MOVING message handler will stop the form from being moved off screen.