文本宽度后的复选框大小

时间:2013-09-25 23:04:55

标签: c++ winapi

我有这个

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

并且复选框文本不适合复选框大小。

CB Testing!

我可以以某种方式设置文本宽度后的复选框宽度吗?

2 个答案:

答案 0 :(得分:7)

在某些MSDN浏览中发现了这个精彩的消息!

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);

答案 1 :(得分:3)

您需要使用GetTextExtentPoint32来获取字符串的大小,然后您需要使用带有SM_CXMENUCHECK的GetSystemMetrics来添加复选框本身的大小:

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