How to move a circle with a mouse in delphi?

How to move a circle with the mouse in delphi?

circle:Shape;
+3
source share
3 answers

Be sure to convert the coordinates of the X, Y mouse click that you get from MouseMove to your control on the parent client using ClientToScreenand ScreenToClient.

The following procedure moves the center of the control to the point (X, Y) in its 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 on click, you need 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 verify this, release the button in your form using 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;

, , .
MouseMove...: -)

+6

, , , - , , :

- IsFollowingMouse. , . MouseMove :

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;

Offsets are the variables that you use, which gives the difference between the location of the mouse pointer and the upper left corner of TShape.

0
source

Source: https://habr.com/ru/post/1735507/


All Articles