在 Inno Setup Pascal 脚本中获取字符串的宽度和高度

Get width and height of a string in Inno Setup Pascal Script

我能在 Pascal 脚本中获取字符串的宽度和高度吗?

例如:

var
  S: String;

S := 'ThisIsMyStringToBeChecked'

这里我需要return它的高度和宽度根据它当前的字体大小和字体。

我阅读了 How to get TextWidth of string (without Canvas)?,但无法将其转换为 Inno Setup Pascal 代码。

我希望此测量值(宽度和高度)在标题字符串的宽度超过 TLabel.Width 时将 TLabel.Caption 更改为 'Too Long To Display'clRed

提前致谢。

以下适用于 TNewStaticText(不是 TLabel):

type
  TSize = record
    cx, cy: Integer;
  end;

function GetTextExtentPoint32(hdc: THandle; s: string; c: Integer;
  var Size: TSize): Boolean;
  external 'GetTextExtentPoint32W@Gdi32.dll stdcall';
function GetDC(hWnd: THandle): THandle;
  external 'GetDC@User32.dll stdcall';
function SelectObject(hdc: THandle; hgdiobj: THandle): THandle;
  external 'SelectObject@Gdi32.dll stdcall';

procedure SmartSetCaption(L: TNewStaticText; Caption: string);
var
  hdc: THandle;
  Size: TSize;
  OldFont: THandle;
begin
  hdc := GetDC(L.Handle);
  OldFont := SelectObject(hdc, L.Font.Handle);
  GetTextExtentPoint32(hdc, Caption, Length(Caption), Size);
  SelectObject(hdc, OldFont);

  if Size.cx > L.Width then
  begin
    L.Font.Color := clRed;
    L.Caption := 'Too long to display';
  end
    else
  begin
    L.ParentFont := True;
    L.Caption := Caption;
  end;
end;