Search code examples
delphimousecoordinatesfiremonkeytstringgrid

Firemonkey MouseToCell equivalent


In Delphi VCL if I wanted to see which cell (column and row) of a TStringGrid my mouse was hovering over I'd use MouseToCell. This method is no longer in Delphi (XE2) for FireMonkey apps. Does anyone know how I can determine the cell my mouse is over? OnMouseMove has X & Y values but these are screen coordinates and not cell coordinates.

Many thanks.


Solution

  • There's actually a MouseToCell method in TCustomGrid, which the StringGrid descends, but it's private. Looking at its source, it makes use of ColumnByPoint and RowByPoint methods, which are fortunately public.

    The 'column' one returns a TColumn, or nil if there's no column. The 'row' one returns a positive integer, or -1 when there's no row. Furthermore, the row one does not care the row count, it just accounts for row height and returns a row number based on this, even if there are no rows. Also, I should note that, behavior on grid header is buggy. Anyway, sample example could be like:

    procedure TForm1.StringGrid1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Single);
    var
      Col: TColumn;
      C, R: Integer;
    begin
      Col := StringGrid1.ColumnByPoint(X, Y);
      if Assigned(Col) then
        C := Col.Index
      else
        C := -1;
      R := StringGrid1.RowByPoint(X, Y);
    
      Caption := Format('Col:%d Row:%d', [C, R]);
    end;