Search code examples
inno-setuppascalscript

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


Is there anyway I can get width and height of a string in Pascal Script?

Eg:

var
  S: String;

S := 'ThisIsMyStringToBeChecked'

Here I need to return its height and width according to its current font size and font.

I read How to get TextWidth of string (without Canvas)?, but can't convert it to an Inno Setup Pascal code.

I want this measurements (width and height) to change the TLabel.Caption like 'Too Long To Display' with clRed when width of the string of its caption exceeds TLabel.Width.

Thanks in advance.


Solution

  • The following works for the TNewStaticText (not the 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;