Limiting mouse cursor movement

Posted by webmaster Guido on February 16, 2007

In Reply to Re: Code and skinning posted by Graham J Hadlington p12555 on February 15, 2007
When there is a mouseclick in the rectangle please.
Limited to the bounds of the rectangle until the random number has been generated in the editbox.

For the rectangle, you can use any visual component that has an OnClick event. In the following example, we use a Panel component for the rectangle, and a Timer object for, ...er, well, the timing :)

In order to make this message easier to read, we renamed the panel to P.

  1. Drop a TPanel on the form and set its property Cursor to crHandPoint.
  2. Drop a TTimer on the form and set its property Enabled to False.
  3. When the Panel is clicked and the Timer is not enabled, we set the Timer's interval to a random value in milliseconds, e.g. something between about 1 second and 6 seconds. We also change the color of the panel. In the Object Inspector, create an OnClick event for the panel and complete the source code as follows:
    procedure TForm1.PClick(Sender: TObject);
    begin
      if not Timer1.Enabled then begin
        Timer1.Interval := 1000 + Random(5000);
        Timer1.Enabled := True;
        P.Color := clRed;
      end;
    end; 
    Of course, you could give another visual feedback, such as changing the panel's caption, or the caption of some other component such as a label, to "The mouse cursor is trapped".
  4. After the specified interval, we disable the timer and we revert the color of the panel back to its default color. In the Object Inspector, create an OnTimer event for the timer and complete it as follows:
    procedure TForm1.Timer1Timer(Sender: TObject);
    begin
      Timer1.Enabled := False;
      P.Color := clBtnFace;
    end;
  5. Finally, here's the routine that makes it all happen. In the Object Inspector, create an OnMouseMove event for the form and complete it as follows:
    procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    var
      MPClient: TPoint; // mouse-cursor position X and Y in CLIENT coordinates
    begin
      if Timer1.Enabled then begin
        MPClient := ScreenToClient(Mouse.CursorPos);
        if X < P.Left then MPClient.X := P.Left + 2;
        if X > P.Left + P.Width then MPClient.X := P.Left + P.Width - 2;
        if Y < P.Top then MPClient.Y := P.Top + 2;
        if Y > P.Top + P.Height then MPClient.Y := P.Top + P.Height - 2;
        Mouse.CursorPos := ClientToScreen(MPClient);
      end;
    end; 

Guido, DelphiLand Team

Related articles

       

Follow Ups