delphiclickstringgrid

Delphi XE3 stringgrid fixed cell click event doesn't fire


I have a StringGrid component in Delphi. I would like to catch when user clicks to the fixed cells (header).

When I bound FixedCellClick event to the grid, event can only detects the click using the left button of the mouse. If I try that with the right button, nothing happens.

procedure TForm1.StringGrid1FixedCellClick(Sender: TObject; ACol, ARow: Integer);
begin
  ShowMessage('');
end;

What is the solution?


Solution

  • As you have found, the Click events are typically associated with left-mouse button actions. To handle mouse button events more generally the Mouse events are more useful.

    In this case you can use the OnMouseButtonDown event.

    NOTE: This does not exactly correspond to a "click" since it occurs in response to the initial mouse down event, rather than reliably responding to a mouse-down-followed-by-a-mouse-up in the same region of a control.

    However, it is often good enough.

    The OnMouseButtonDown event includes a parameter that identifies the Button involved and the mouse X and Y positions. It also include a ShiftState to detect Ctrl and/or Shift key states during the event (if relevant).

    You can use these to detect a right-mouse button being pressed in your fixed rows/columns:

    procedure TfrmMain.StringGrid1MouseDown(Sender: TObject;
                                            Button: TMouseButton;
                                            Shift: TShiftState;
                                            X, Y: Integer);
    var
      grid: TStringGrid;
      col, row: Integer;
      fixedCol, fixedRow: Boolean;
    begin
      grid := Sender as TStringGrid;
    
      if Button = mbRight then
      begin
        grid.MouseToCell(X, Y, col, row);
    
        fixedCol := col < grid.FixedCols;
        fixedRow := row < grid.FixedRows;
    
        if   (fixedCol and fixedRow) then
          // Right-click in "header hub"
    
        else if fixedRow then
          // Right-click in a "column header"
    
        else if fixedCol then
          // Right-click in a "row header"
    
        else
          // Right-click in a non-fixed cell
      end;
    end;