2009. november 1., vasárnap

How to implement a multi-line caption on a TButton


Problem/Question/Abstract:

How do I make a button have a two line caption? I think there is a character or sequence there to embed a linefeed in the caption property.

Answer:

It is not as simple as adding a #13#10 sequence as a line break in the caption. You also need to add the BS_MULTILINE style. The following sample component will accept a pipe character ("|") in the caption as proxy for a linebreak. This allows you to specify the break in the designer, which does not accept Return as part of the caption string.

unit MLButton;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;

type
  TMultilineButton = class(TButton)
  private
    FMultiline: Boolean;
    function GetCaption: string;
    procedure SetCaption(const Value: string);
    procedure SetMultiline(const Value: Boolean);
  public
    procedure CreateParams(var params: TCreateParams); override;
    constructor Create(aOwner: TComponent); override;
  published
    property Multiline: Boolean read FMultiline write SetMultiline default True;
    property Caption: string read GetCaption write SetCaption;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('PBGoodies', [TMultilineButton]);
end;

constructor TMultilineButton.Create(aOwner: TComponent);
begin
  inherited;
  FMultiline := True;
end;

procedure TMultilineButton.CreateParams(var params: TCreateParams);
begin
  inherited;
  if FMultiline then
    params.Style := params.Style or BS_MULTILINE;
end;

function TMultilineButton.GetCaption: string;
begin
  Result := Stringreplace(inherited Caption, #13, '|', [rfReplaceAll]);
end;

procedure TMultilineButton.SetCaption(const Value: string);
begin
  if value <> Caption then
  begin
    inherited Caption := Stringreplace(value, '|', #13, [rfReplaceAll]);
    Invalidate;
  end;
end;

procedure TMultilineButton.SetMultiline(const Value: Boolean);
begin
  if FMultiline <> Value then
  begin
    FMultiline := Value;
    RecreateWnd;
  end;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése