Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox size after text width

Tags:

c++

winapi

I have this

CreateWindowA("BUTTON", "Testing!", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, 0, 0, 45, 20, hwnd, 0, 0, 0);

and the checkbox text does not fit inside the checkbox size.

CB Testing!

Can i somehow set the checkbox width after the text width?

like image 250
Christopher Janzon Avatar asked Dec 20 '22 23:12

Christopher Janzon


2 Answers

Found this wonderful message deep in some MSDN browsing!

BCM_GETIDEALSIZE

HWND cbhwnd = CreateWindowA("BUTTON", "Testing!", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, 0, 0, 0, 0, hwnd, 0, 0, 0);
SIZE size;
SendMessage(cbhwnd, BCM_GETIDEALSIZE, 0, &size);
SendMessage(cbhwnd, WM_SIZE, 0, size);
like image 56
Christopher Janzon Avatar answered Dec 22 '22 14:12

Christopher Janzon


You need to use GetTextExtentPoint32 to get the size of the string, then you need to add the size of the checkbox itself by using GetSystemMetrics with SM_CXMENUCHECK:

HDC hDc = GetDC(hWnd);
HFONT hCurrentFont;
HFONT hNewFont = (HFONT)GetStockObject(SYSTEM_FONT); //Change this if you want to use a different font!
if(hCurrentFont = (HFONT)SelectObject(hDc, hNewFont))
{
    SIZE stringSize;
    if(GetTextExtentPoint32A(hDc, "Testing!", sizeof("Testing!"), &stringSize))
    {
        int totalWidth = stringSize.cx + GetSystemMetrics(SM_CXMENUCHECK);
        int totalHeight = stringSize.cy;
        CreateWindowA("BUTTON", "Testing!", WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, 
                          0, 0, totalWidth, totalHeight, hWnd, 0, 0, 0);
    }
    else
    {
        //error! unable to get size
    }
}
else
{
    //error! unable to get font
}
hNewFont = (HFONT)SelectObject(hDc, hCurrentFont);

DeleteObject(hNewFont);
ReleaseDC(hWnd, hDc); //Release DC
like image 26
Sam Cristall Avatar answered Dec 22 '22 12:12

Sam Cristall