How do I determine the height of a line of text in a TMemo programmatically?

前端 未结 4 1775
小蘑菇
小蘑菇 2020-12-22 01:21

I\'ve got a TMemo, and I want to always make it exactly high enough to display the number of lines it contains. Unfortunately, I don\'t quite know how to calculate that. I

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 01:54

    You can write your own implementation of TCanvas.TextHeight for TMemo:

    function CountMemoLineHeights(Memo: TMemo): Integer;
    var
      DC: HDC;
      SaveFont: HFont;
      Size: TSize;
      I: Integer;
    
    begin
      DC:= GetDC(Memo.Handle);
      SaveFont:= SelectObject(DC, Memo.Font.Handle);
      Size.cX := 0;
      Size.cY := 0;
    //  I have not noticed difference in actual line heights for TMemo,
    //    so the next line should work OK
      Windows.GetTextExtentPoint32(DC, 'W', 1, Size);
    //  BTW next (commented) line returns Size.cY = 0 for empty line (Memo.Lines[I] = '') 
    //    Windows.GetTextExtentPoint32(DC, Memo.Lines[I], Length(Memo.Lines[I]), Size);
      Result:= Memo.Lines.Count * Size.cY;
      SelectObject(DC, SaveFont);
      ReleaseDC(Memo.Handle, DC);
    end;
    

提交回复
热议问题