unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, LMessages,
StdCtrls, ExtCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Panel1: TPanel;
Button1: TButton;
StringGrid1: TStringGrid;
procedure Button1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
GridLastCol, GridLastRow: Integer;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormShow(Sender: TObject);
var
i, j: Integer;
begin
Caption := 'TStringGrid - OnMouseDown Test';
Height := 500;
Width := 1000;
Panel1.Caption := '';
Panel1.Align := alTop;
Panel1.Height := Button1.Height * 2;
Panel1.Color := clYellow;
Button1.Caption := 'Last clicked cell';
Button1.Top := Panel1.Height div 4;
Button1.Left := 10;
Button1.AutoSize := True;
StringGrid1.Align := alClient;
StringGrid1.ColCount := 12;
StringGrid1.RowCount := 19;
StringGrid1.FixedCols := 0;
StringGrid1.FixedRows := 0;
// (Optional) Adjust automatic or fixed widths
StringGrid1.ColWidths[0] := 80;
// Optional: Set headers in the first row (fixed)
for i := 0 to StringGrid1.ColCount - 1 do
begin
StringGrid1.Cells[i, 0] := 'Row ' + IntToStr(i + 1);
// (Optional) Adjust automatic or fixed widths
if (i = 0) then
StringGrid1.ColWidths[0] := 75
else
StringGrid1.ColWidths[i] := 80;
end;
// Optional: Set headers in the first column (fixed)
for i := 0 to StringGrid1.RowCount - 1 do
begin
StringGrid1.Cells[0, i] := 'Column ' + IntToStr(i + 1);
end;
// Optional: Fill data cells
for i := 01 to StringGrid1.ColCount - 1 do
begin
for j := 1 to StringGrid1.RowCount - 1 do
begin
StringGrid1.Cells[i, j] := 'Cell[' + IntToStr(i + 1) + ', ' + IntToStr(j + 1) + ']';
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Last clicked cell: Column ' + IntToStr(GridLastCol) +
', Row ' + IntToStr(GridLastRow) + LineEnding +
StringGrid1.Cells[GridLastCol, GridLastRow]);
end;
procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
ACol, ARow: Integer;
begin
if Button = mbRight then
begin
// Simulate a left-click to update Row/Col to the cell under the mouse
// Delphi StringGrid1.Perform(WM_LBUTTONDOWN, 0, MakeLParam(Word(X), Word(Y)));
StringGrid1.Perform(LM_LBUTTONDOWN, 0, LongInt(Word(X) or (Word(Y) shl 16)));
end;
// Convert mouse coordinates to cell indices
StringGrid1.MouseToCell(X, Y, ACol, ARow);
// Display the result
ShowMessage('Clicked Cell: Column ' + IntToStr(ACol) +
', Row ' + IntToStr(ARow) + LineEnding +
StringGrid1.Cells[ACol, ARow]);
// Store information about last clicked cell
GridLastCol := ACol;
GridLastRow := ARow;
if Button = mbRight then
begin
// Cancel last simulated left-click to update Row/Col to the cell under the mouse
StringGrid1.Perform(LM_LBUTTONUP, 0, LongInt(Word(X) or (Word(Y) shl 16)));
end;
end;
end.