You can trap the OnMouseDown event, remembering the x and y
coordinates of the mouse and set the mouse capture. You can
then track mouse movements with the OnMouseMove event,
moving the control until the OnMouseUp event is fired. You then
will want to place the control in it's final position and release
capture of the mouse.
The following example shows how to move a TButton component
around on the form using the mouse. The movement is initiated by
the user holding down the control key when the mouse button is
activated.
Example:
type
TForm = class(TForm)
Button : TButton;
procedure Button MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Button MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Button MouseUp(Sender: TObject; Button:
TMouseButton; Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
MouseDownSpot : TPoint;
Capturing : bool;
end;
var
Form : TForm ;
implementation
{$R *.DFM}
procedure TForm .Button MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if ssCtrl in Shift then begin
SetCapture(Button .Handle);
Capturing := true;
MouseDownSpot.X := x;
MouseDownSpot.Y := Y;
end;
end;
procedure TForm .Button MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Capturing then begin
Button .Left := Button .Left - (MouseDownSpot.x - x);
Button .Top := Button .Top - (MouseDownSpot.y - y);
end;
end;
procedure TForm .Button MouseUp(Sender: TObject; Button:
TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Capturing then begin
ReleaseCapture;
Capturing := false;
Button .Left := Button .Left - (MouseDownSpot.x - x);
Button .Top := Button .Top - (MouseDownSpot.y - y);
end;
end;
7/ 6/98 4:3 :28 PM