Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!
Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.
Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!
[Solved] Lazarus/Delphi - Dragging a TShape over your TForm
Delphi, Lazarus, Free Pascal
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter
February 13, 2015 1:02 AM
I'm working on a little project where I need to be able to drag a TShape (or any other visual component for that matter) and it rook me a bit to figure out how to make it draggable.
First step is to create or place a TShape (or other visual component) on your Form (or TPanel, or which ever) - I named mine: MyShape.
Next we need to add a global variable to capture Mouse position for when draging starts. I've used a TPoint for that (holds X and Y) and placed it in the private part of the TForm declaration. We need this to store a mouse location so we can determine where the mouse moved to.
private
{ private declarations }
MouseOriginatePosition : TPoint;
Next, set the property "DragMode" of the TShape to "dmAutomatic".
After that add code to the "
OnMouseDown" event of the TShape:
procedure TForm1.MyShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
MouseOriginatePosition.X := X;
MouseOriginatePosition.Y := Y;
end;
And we need to add code to the "OnMouseMove" event of the TShape:
procedure TForm1.MyShapeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if Mouse.IsDragging then
begin
TShape(Sender).Left := TShape(Sender).Left + X - MouseOriginatePosition.X;
TShape(Sender).Top := TShape(Sender).Top + Y - MouseOriginatePosition.Y;
end;
end;
And that's all there is to it.
Run your application and click and drag your TShape (or other component) however you'd like.
In case you didn't use a TShape, make sure to adapt the 2 lines with the type cast to the type you're using. For example TPanel(Sender) in stead of TShape(Sender).
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter
February 13, 2015 4:55 AM
A good and cleaner (more readable) method for the type casting might be:
procedure TForm1.MyShapeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if Mouse.IsDragging then
with (Sender as TShape) do
begin
Left := Left + X - MouseOriginatePosition.X;
Top := Top + Y - MouseOriginatePosition.Y;
end;
end;