1
votes

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.

1

1 Answers

1
votes

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 '[email protected] stdcall';
function GetDC(hWnd: THandle): THandle;
  external '[email protected] stdcall';
function SelectObject(hdc: THandle; hgdiobj: THandle): THandle;
  external '[email protected] 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;