4

In a Delphi 10.4.2 Win32 VCL Application on Windows 10, I have a TButton with WordWrap = True and Caption = 'SAVE TO INTERNET BOOKMARKS FOLDER...':

image

As you can see from the screenshot, the height of the button does not automatically fit its Caption text.

Is there a feature in TButton to achieve this automatically, or do I have to adjust this manually?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
user1580348
  • 5,721
  • 4
  • 43
  • 105

1 Answers1

10

No, there is no automatic adjustment of the height of a TButton offered by the VCL.

If you change the font of the button's caption, or make it multi-line, you typically have to adjust the button's height yourself explicitly.

As a comparison, TEdit does have an AutoSize property. This doesn't map to a feature of the Win32 EDIT control (like a window style), but is implemented purely in the VCL (see Vcl.StdCtrls.TCustomEdit.AdjustHeight()).

However, I just discovered that the underlying Win32 BUTTON control does offer this functionality, via the BCM_GETIDEALSIZE message or Button_GetIdealSize() macro:

uses
  ..., Winapi.CommCtrl;

var
  S: TSize;
begin
  S.cx := Button1.Width;
  if Button_GetIdealSize(Button1.Handle, S) then
    Button1.Height := S.cy;

This will set the height given the button's current text and desired width. If S is initially zeros, you get the button's preferred width and height.

It is not uncommon that a Win32 control offers more functionality than its VCL wrapper exposes, so it is often a good idea to have a look at the Win32 documentation, particularly the messages you can send to the control (and also its styles).

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • It works perfectly! Where do you get all these "magical" solutions? – user1580348 Aug 04 '21 at 21:39
  • @user1580348: I added that to the A. – Andreas Rejbrand Aug 04 '21 at 21:41
  • 1
    Just looking at available styles and their documentation I use button-like checkboxes for decades already: `SetWindowLong( checkbox.Handle, GWL_STYLE, GetWindowLong( checkbox.Handle, GWL_STYLE ) or BS_PUSHLIKE );` - makes a great "run/stop" button. – AmigoJack Aug 05 '21 at 00:50
  • BTW, here is the result: https://i.imgur.com/c8J6kAc.png – user1580348 Aug 05 '21 at 07:24
  • @AmigoJack It would be nice if it would keep the check glyph: https://i.imgur.com/Bjf7guZ.png – user1580348 Aug 05 '21 at 07:30
  • @user1580348 I totally expected that outcome and will continue using it for selected occasions - of course I'm not using it for _every_ checkbox (but instead for occasions where a button alone would not be enough). – AmigoJack Aug 05 '21 at 10:56