How to determine if the mouse cursor is inside a control

前端 未结 3 600
梦如初夏
梦如初夏 2021-02-04 06:22

I\'m adding support for mouse wheel movement to a TScrollBox (using the FormMouseWheel procedure) and I need to determine if the mouse is inside the component.

Basically

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 06:43

    I am using the same method to scroll my scrollboxes using the mouse.

    This is the event handler for the MouseWheel event of the form. It will scroll horizontally if you press shift key while scrolling:

    procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
    var
      Msg: Cardinal;
      Code: Cardinal;
      I, ScrollLines: Integer;    
    begin
      if IsCoordinateOverControl(MousePos, ScrollBox1) then
      begin
        Handled := True;
        If ssShift In Shift Then
          Msg := WM_HSCROLL
        Else
          Msg := WM_VSCROLL;
    
        If WheelDelta < 0 Then
          Code := SB_LINEDOWN
        Else
          Code := SB_LINEUP;
    
        ScrollLines := Mouse.WheelScrollLines * 3;
        for I := 1 to ScrollLines do
          ScrollBox1.Perform(Msg, Code, 0);
        ScrollBox1.Perform(Msg, SB_ENDSCROLL, 0);
      end;
    end;
    

    You can use this function to check if the screen coordinate of the mouse is over your control:

    function IsCoordinateOverControl(screenCoordinate: TPoint; control: TControl): Boolean;
    var
      p: TPoint;
      r: TRect;
    begin
      Result := False;
      p := control.ScreenToClient(screenCoordinate);
      r := Rect(0, 0, control.Width, control.Height);
      if PtInRect(r, p) then
        Result := True;
    end;
    

提交回复
热议问题