Recent

Author Topic: TMemo text width  (Read 540 times)

Kaller

  • Jr. Member
  • **
  • Posts: 73
TMemo text width
« on: September 28, 2023, 11:42:01 am »
TMemo does not seem to expose a canvas property, I want to calculate the text width of a Memo line given font etc. I was thinking maybe I need a temporary canvas or something just to do the calculation. What's the best way to go about it?

wp

  • Hero Member
  • *****
  • Posts: 11760
Re: TMemo text width
« Reply #1 on: September 28, 2023, 12:50:05 pm »
You could temporatily create a bitmap, or a TControlCanvas for the control under investigation:

Code: Pascal  [Select][+][-]
  1. function GetControlTextWidth(AControl: TControl; AText: String): Integer;
  2. var
  3.   c: TControlCanvas;
  4. begin
  5.   c := TControlCanvas.Create;
  6.   try
  7.     c.Control := AControl;
  8.     c.Font.Assign(AControl.Font);
  9.     Result := c.TextWidth(AText);
  10.   finally
  11.     c.Free;
  12.   end;
  13. end;
  14.  
  15. procedure TForm1.Button1Click(Sender: TObject);
  16. var
  17.   w: Integer;
  18. begin
  19.   w := GetControlTextWidth(Memo1, 'Memo1');
  20.   ShowMessage(w.ToString);
  21. end;

 

TinyPortal © 2005-2018