Posted by webmaster Guido In Reply to Center text in cell of stringgrid In the OnDrawCell event handler, we set the text-alignment of the stringgrid's canvas with the Windows API function SetTextAlign(CanvasHandle, AlignmentMode). The return value of this function is the previous text-alignment setting; we save it temporarily. Next, we write the contents of the cell with Canvas.TextRect(Rect, X, Y, S). Any portions of the string S that fall outside the rectangle passed in the Rect parameter are clipped. The upper left corner of the text is placed at the point (X, Y). Finally, we reset the text-alignment to the saved value. Here's a Delphi source code example: procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var S: string; SavedAlign: word; begin if ACol = 1 then begin // ACol is zero based S := StringGrid1.Cells[ACol, ARow]; // cell contents SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_CENTER); StringGrid1.Canvas.TextRect(Rect, Rect.Left + (Rect.Right - Rect.Left) div 2, Rect.Top + 2, S); SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign); end; end; If you want right-aligned column, use the following source code: procedure TForm1.StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
S: string;
SavedAlign: word;
begin
if ACol = 1 then begin
S := StringGrid1.Cells[ACol, ARow]; // cell contents
SavedAlign := SetTextAlign(StringGrid1.Canvas.Handle, TA_RIGHT);
StringGrid1.Canvas.TextRect(Rect, Rect.Right - 2, Rect.Top + 2, S);
SetTextAlign(StringGrid1.Canvas.Handle, SavedAlign);
end;
end;
Related articles
|