delphidelphi-10-seattleonmousemovetimage

How detect if i'm moving mouse to left, right, top or bottom inside TImage component on mousemove event?


I want know how detect to what side i'm moving mouse: to left, right, top, bottom inside TImage component on mousemove event?

Thank you.


Solution

  • Here's an example to be used in an FMX project. For a VCL project, you would use integer variables.

    First, declare two variables Xold, Yold: single; for example in the private section of the form.

    private
      Xold, Yold: Single;
    

    Initialize these variables e.g. in the forms OnCreate() event. Using NaN requires System.Math in the uses clause.

    procedure TForm5.FormCreate(Sender: TObject);
    begin
      Xold := NaN;
      Yold := NaN;
    end;
    

    Then, in the OnMouseMove() event, calculate the movement horizontally and vertically, negative value indicate moving left or up, positive right or down.

    procedure TForm5.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Single);
    var
      horz, vert: Single;
    begin
      if not IsNan(Xold) then horz := X - Xold else horz := 0;
      if not IsNan(Yold) then vert := Y - Yold else vert := 0;
      Xold := X; // save new values
      Yold := Y; //
      // use horz and vert as needed
      Label1.Text := Format('h: %f, v: %f',[horz, vert]);
    end;
    

    You may also want to reset the Xold and Yold variables to NaN when the mouse leaves the image.

    procedure TForm5.Image1MouseLeave(Sender: TObject);
    begin
      Xold := NaN;
      Yold := NaN;
    end;
    

    It was asked in comments, why initialize to NaN instead of just zero? Xold := 0; Yold := 0 is the top-left corner. If the mouse entry to the image happens at e.g. right side, the first move would be a jump from 0 to image width. Using NaN we can omit the first entry as a move and just store the entry point in Xold and Yold for use with next move.