2006. március 25., szombat

How to make a TButton flee from the mouse cursor


Problem/Question/Abstract:

As a joke, I am trying to have a button on a form move around the form to avoid the mouse pointer. I was trying to use the OnMouseMove event of the form to accomplish this, but have not had any success. Does anybody know a quick way of doing this?

Answer:

procedure TMainForm.Button1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  NewPoint: TPoint;
begin
  Randomize;
  NewPoint.X := X;
  NewPoint.Y := Y;
  repeat
    NewPoint.X := NewPoint.X + Random((Sender as TButton).Width div 2);
    NewPoint.Y := NewPoint.Y + Random((Sender as TButton).Height div 2);
  until
    PtInRect(ClientRect, NewPoint) and not PtInRect((Sender as TButton).ClientRect, NewPoint);
  (Sender as TButton).Left := NewPoint.X;
  (Sender as TButton).Top := NewPoint.Y;
end;

Nincsenek megjegyzések:

Megjegyzés küldése