Search code examples
delphi

Newline character in caption of button


I am building an application in which I want to display a button on a form. I want to display the Caption of the button on two lines. I have tried using the following code in the form's OnCreate event but it is not showing the new line.

Button.Caption := 'Hello' + #13#10 + 'world';

Any other method to add a new line?


Solution

  • For very old Delphi versions which do not have the WordWrap property:

    Use following code prior to setting the caption:

    SetWindowLong(Button1.Handle, GWL_STYLE, 
      GetWindowLong(Button1.Handle, GWL_STYLE) or BS_MULTILINE);
    

    But the tricky part is that this code needs execution on a number of occasions. When the button is recreated, then your multiline setting is lost. Kind of similar to this dilemma.

    Luckily the VCL provides a solution, but you have to subclass the TButton type, e.g. as follows:

    type
      TButton = class(StdCtrls.TButton)
      protected
        procedure CreateParams(var Params: TCreateParams); override;
      end;
    
      TForm1 = class(TForm)
    
    ...
    
    procedure TButton.CreateParams(var Params: TCreateParams);
    begin
      inherited CreateParams(Params);
      Params.Style := Params.Style or BS_MULTILINE;
    end;