how to move circle with mouse in delphi? circle:Shape;
Well, I don't have too much to go on, but having something move to follow the mouse generally works like this:
Have a "IsFollowingMouse" flag somewhere. Turn it on when you should be following the mouse. On the form's MouseMove event, do something like this:
procedure TMyForm.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FIsFollowingMouse then
begin
myCircle.left := x + fShapeOffsetX;
myCircle.top := y + fShapeOffsetY;
end;
end;
The offsets are variables you use that gives the difference between the location of the mouse pointer and the top-left corner of the TShape.
Be sure to convert the Mouse X,Y client coordinates that you get from MouseMove on your Control to the Parent's client using ClientToScreen
and ScreenToClient
.
The following procedure moves the center of a Control to the point (X,Y) in it's client coordinates:
procedure MoveControl(AControl: TControl; const X, Y: Integer);
var
lPoint: TPoint;
begin
lPoint := AControl.Parent.ScreenToClient(AControl.ClientToScreen(Point(X, Y)));
AControl.Left := lPoint.X - AControl.Width div 2;
AControl.Top := lPoint.Y - AControl.Height div 2;
end;
Now to move your TShape when when it is clicked, you have to provide the following MouseMove event handler:
procedure TForm1.ShapeToMoveMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then // only move it when Left-click is down
MoveControl(Sender as TControl, X, Y);
end;
And to test it, drop a button in your Form with this code:
procedure TForm1.ButtonTestClick(Sender: TObject);
begin
with TShape.Create(nil) do
begin
Name := Format('ShapeToMove%d',[Self.ControlCount + 1]);
Parent := Self; // Parent will free it
Shape := stCircle;
Width := 65;
Height := 65;
OnMouseMove := ShapeToMoveMouseMove;
end;
end;
Now, that's a minimalist example, but it should get you started.
For fun, just hook other controls with this MouseMove event handler... :-)
If you go to my webpage, you can Find some samples (all with code included) thah can help you about this question. "Sample for visual work with figures and plans"; Use two components for manage, move, resize and save elements visually; One for selection, movement, resize,... (TSeleccOnRuntime) and other (TSaveComps) for save the state (position, size,...).
Select Shapes Visually; Sample for explain two modes for select visually shapes and images.
Create, move and resive controls on Runtime (like IDE); Another sample of TSeleccOnRuntime component. Simulate and IDE.
And finally another sample for Create/destroy components in runtime and move with mouse; This sample is made without components. All code at the sample.
I hope that is usefull for you.
Regards
P.D: Excuse for my bad english.
There are several good answers here.
If you decide to code your own, I found this to be a good starting point.