2

Possible Duplicate:
Can I make a TMemo size itself to the text it contains?

Need to do autosize memo: height and width.

I autosize the height as follows:

function TForm1.AutoSizeMemoY(Memo: TMemo): word;
begin
  Canvas.Font := Memo.Font;
  Result := Canvas.TextExtent(Memo.Lines.Strings[0]).cy * Memo.Lines.Count +
    Canvas.TextExtent(Memo.Lines.Strings[0]).cy;
end;

But I do not know how to do autosize the width. I have an idea: if the scrollbar is activated, then increase the width until it becomes inactive, but I do not know how to implement that.

Community
  • 1
  • 1
dedoki
  • 709
  • 4
  • 14
  • 24
  • 2
    Austosizing can only be achieved in one direction. Either you fix the height and adjust the width or fix the width and adjust the height. – hubalazs Jun 20 '12 at 10:00
  • @SimaWB, I need to, and in width, and height. + font can be different! – dedoki Jun 20 '12 at 12:09

1 Answers1

3

Not the best solution but it works:

function GetTextWidth(F: TFont; s: string): integer;
var
  l: TLabel;
begin
  l := TLabel.Create(nil);
  try
    l.Font.Assign(F);
    l.Caption := s;
    l.AutoSize := True;
    result := l.Width + 8;
  finally
    l.Free;
  end;
end;

And add following code to the end of Memo1.Onchange event in this answer

  LineInd := Memo1.Perform(EM_LINEFROMCHAR, Memo1.SelStart, 0);//focused Memo1 line Index
  Wd := GetTextWidth(Memo1.Font, Memo1.Lines[LineInd]);
  //MaxWidthLineInd = index of the line which has the largest width. 
  //Init value of MaxWidthLineInd = 0
  if MaxWidthLineInd = LineInd then 
    Memo1.Width := Wd
  else begin
    if Wd > Memo1.Width then
    begin
      Memo1.Width := Wd;
      MaxWidthLineInd := LineInd;
    end;
  end;
Community
  • 1
  • 1
SimaWB
  • 9,246
  • 2
  • 41
  • 46