Examples Delphi

Title: Playing with style - Part 3
Question: How do I get a button with multiline caption?
Answer:
Once again, playing with style bits.
Using the same technique shown in my other articles, you can add the BS_MULTILINE bit to the styles of an existing button (or a check box, or a radio button). This enable the control to recognize the CR/LF pairs embedded in the caption text.
You can try using this procedure:
procedure Multiline(theControl: TWinControl);
var
dwStyle: Longint;
begin
dwStyle := GetWindowLong(theControl.handle, GWL_STYLE) or BS_MULTILINE;
SetWindowLong(theControl.Handle, GWL_STYLE, dwStyle);
end;
As usual you can derive a new button class from TButton (or TRadioButton, or TCheckBox) to automatically obtain a multiline caption button
unit MultilineButton;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TMultilineButton = class(TButton)
private
{ Private declarations }
protected
{ Protected declarations }
procedure CreateParams(var Params: TCreateParams); override;
public
{ Public declarations }
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Bigpepe', [TMultilineButton]);
end;
{ TMultilineButton }
procedure TMultilineButton.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := Params.Style or BS_MULTILINE;
end;
end.
Unfortunately, the property editor for caption does not accept CR or LF characters so you must set the caption at run-time in this way:
...
MyButton.Caption := 'Hello, '#13#10'world!';
...
Alternatively you can use a function to replace a pipe character (or any other character) with a CR/LF pair. Here's one:
function SplitCaption(theCaption: string): string;
begin
Result := StringReplace(theCaption, '|', #13#10, [rfReplaceAll]);
end;
This may simplify your code because you can set the caption at design time using the regular editor, and replace the caption at run time in this way:
MyButton.Caption := SplitCaption(MyButton.Caption);
Of course, as a better alternative, you can write a property editor that accepts the CR/LF pairs to replace the standard editor... but this is another story.
Enjoy!