Author: Ernesto De Spirito
How can I prevent the user from moving the form outside screen boundaries to
guarantee the form is always visible inside the screen work area?
Answer:
We can know if a form has resized with the Resize event (OnResize property), but
how do we know if a form has moved? Simply by capturing the WM_MOVE Windows message.
In the message event we call "inherited" to let the ancestors of TForm process the
message. This will update the Left and Top properties that we can use along with
Width and Height to see if the form is placed within the limits of the screen's
work area (the portion of the screen not used by the system taskbar or by
application desktop toolbars) and move it if not.
1 2 procedure TfrmMain.OnMove(var Msg: TWMMove);
3 var4 WorkArea: TRect;
5 begin6 inherited;
7 if SystemParametersInfo(SPI_GETWORKAREA, 0, @WorkArea, 0) then8 begin9 if Left < WorkArea.Left then10 Left := WorkArea.Left
11 elseif Left + Width > WorkArea.Right then12 Left := WorkArea.Right - Width;
13 if Top < WorkArea.Top then14 Top := WorkArea.top
15 elseif Top + Height > WorkArea.Bottom then16 Top := WorkArea.Bottom - Height;
17 end;
18 end;
The full source code of this example is available for download:
http://www.latiumsoftware.com/download/p0020.zip
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php