2006. július 30., vasárnap

Display a long text in a TLabel with an end ellipsis


Problem/Question/Abstract:

How to display a long text in a TLabel with an end ellipsis

Answer:

You must turn off AutoSize for the label, of course. Otherwise the current content of the label determines where the string will be trimmed.

{ ... }
var
  S: string;
  R: TRect;
  { ... }
begin
  {Get the text you want into S}
  S := 'this is way too long to fit into a label - trim it down';
  {Make it unique, because DrawText is going to change it}
  UniqueString(S);
  {Get the rectangle available for drawing}
  R := Label1.ClientRect;
  {Make sure you're using the same font the label will use}
  Label1.Canvas.Font := Label1.Font;
  {Ask Windows to trim it up with out replacing "&" by an underscore}
  DrawText(Label1.Canvas.Handle, PChar(S), Length(S), R, DT_END_ELLIPSIS or
    DT_MODIFYSTRING or DT_NOPREFIX);
  {Now plug that trimmed text into Label1}
  Label1.Caption := S;
  { ... }

Nincsenek megjegyzések:

Megjegyzés küldése