4

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?

Alberto Rossi
  • 1,800
  • 4
  • 36
  • 58

1 Answers1

5

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.

TLama
  • 75,147
  • 17
  • 214
  • 392
  • http://prntscr.com/1k9vrr look at here, I've applied your code only on the 1st table. If you see, it has a strange layout. How could I fix it? (+1 and will accept) – Alberto Rossi Aug 09 '13 at 14:30
  • What do you mean with strange layout ? If you mean that themed drawing disappeared, then it's because you're drawing the cells by yourself. – TLama Aug 09 '13 at 14:33
  • can I draw the rest too? – Alberto Rossi Aug 09 '13 at 14:36
  • I don't have Lazarus nor time right now. But yes, you can. The question is how much work will this cost because the `OnDrawCell` is for drawing the whole cells by yourself. And you'd need to ideally draw themed style for every platform (I could help at most with Windows). But now looking at the source code, there is a [`DrawTextInCell`](https://github.com/alrieckert/lazarus/blob/master/lcl/grids.pas#L1539) method which sounds like the one which you might override and draw text however you want without losing themed style. But that's a good topic for a different question... – TLama Aug 09 '13 at 14:45