TA_CENTER not working for center align a StringGrid

delphi, lazarus

Solution

Since you're using Lazarus, I wouldn't rely on a platform specific Windows API function, but instead use the built-in canvas `TextRect` method. In (untested) code it might be:

procedure TForm1.StringGrid1DrawCell(Sender: TObject; aCol, aRow: Integer;
  aRect: TRect; aState: TGridDrawState);
var
  CellText: string;
  TextStyle: TTextStyle;
begin
  CellText := StringGrid1.Cells[ACol, ARow];
  StringGrid1.Canvas.FillRect(ARect);

  TextStyle := StringGrid1.Canvas.TextStyle;
  TextStyle.Alignment := taCenter;
  StringGrid1.Canvas.TextRect(ARect, 0, 0, CellText, TextStyle);
  ...    
end;

Anyway, you have used a `TA_CENTER` constant which is used by a different Windows API function, by the `SetTextAlign` function. You should have used the `DT_` ones used by the `DrawText` function.

Problem

I have to center align the text in a StringGrid (its cells) and I'm using the code you see here. I found it in another answer here and I edited some things. ``` procedure TForm1.StringGrid1DrawCell(Sender: TObject; aCol, aRow: Integer; aRect: TRect; aState: TGridDrawState); var LStrCell: string; LRect: TRect; qrt:double; begin LStrCell := StringGrid1.Cells[ACol, ARow]; StringGrid1.Canvas.FillRect(aRect); LRect := aRect; DrawText(StringGrid1.Canvas.Handle, PChar(LStrCell), Length(LStrCell), LRect, TA_CENTER); //other code end; ``` I am using `Lazarus` and it is giving me an error because it doesn't recognize the `TA_CENTER`. Any solutions?

Original source