delphidbgridtdbgrid

Simulate mouse click on a cell in TDBGrid


How can simulate a mouse click on some cell in TDBGrid?


Solution

  • Update:

    This code should do what you seem to want:

    type
      TMyDBGrid = class(TDBGrid);
    
    function TForm1.GetCellRect(ACol, ARow : Integer) : TRect;
    begin
      Result := TmyDBGrid(DBGrid1).CellRect(ACol, ARow);
    end;
    
    procedure TForm1.DBGrid1MouseUp(Sender: TObject; Button: TMouseButton; Shift:
        TShiftState; X, Y: Integer);
    var
      Coords : TGridCoord;    
    begin
      Coords := DBGrid1.MouseCoord(X, Y);
      Caption := Format('Col: %d, Row: %d', [Coords.X, Coords.Y]);
    end;
    
    procedure TForm1.SimulateClick(ACol, ARow : Integer);
    type
      TCoords = packed record
        XPos : SmallInt;
        YPos : SmallInt;
      end;
    var
      ARect : TRect;
      Coords : TCoords;
    begin
      ARect := GetCellRect(ACol, ARow);
      Coords.XPos := ARect.Left;
      Coords.YPos := ARect.Top;
      DBGrid1.Perform(WM_LButtonUp, 0, Integer(Coords));
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      SimulateClick(StrToInt(edX.Text), StrToInt(edY.Text));
    end;
    

    The MouseCoord function of TDBGrid converts a pair of coordinates (X, Y) into a Column number (TGridCoord.X) and a Row number ((TGridCoord.Y).

    The OnMouseUp event displays the results of calling DBGrid1.MouseCoord on the X & Y input arguments.

    The SimulateClick simulates a click on a cell of the grid. It uses GetCellRect to get the coordinates (in the DBGrid) of the topleft of a specified cell and then calls Perform(WM_LButtonUp,...) on the DBGrid, passing the coordinates in the LParam argument.

    Finally Button1Click calls SimulateClick using Col and Row values from a pair of TEdits. That causes the OnMouseUp event to fire and display the Col and Row number, so you can satisfy yourself that it has the same effect as mouse-clicking the corresponding cell.