如何从按钮控件中删除边框并设置复选框背景

时间:2019-04-26 22:48:51

标签: c++ user-interface winapi

我是win32 API的初学者,我做了

HWND button = CreateWindowEx(0, "BUTTON", NULL, WS_CHILD | WS_VISIBLE | BS_BITMAP, 150, 100, 150, 30, hwnd, (HMENU)ID_BUTTON, hInstance, NULL);

HWND check = CreateWindowEx(0, "BUTTON", "text", WS_CHILD | WS_VISIBLE | BS_CHECKBOX, 150, 100, 300, 20, hwnd, (HMENU)ID_CHECK, hInstance, NULL);

我想从插入了位图的按钮控件中删除白色边框,并在BS_CHECKBOX上设置黑色背景和白色文本。我读到有关WM_CTLCOLORBTN的信息,但我不知道如何正确执行。

2 个答案:

答案 0 :(得分:1)

WM_CTLCOLORBTN应该和BS_OWNERDRAW一起使用。

也就是说,仅当添加BS_OWNERDRAW时,WM_CTLCOLORBTN才会被触发并且按钮可以重画。

但是当您使用BS_OWNERDRAW时,原来的复选框样式将被替换,就像这样。

check = CreateWindowEx(0,L"BUTTON",L"text", WS_CHILD | WS_VISIBLE | BS_CHECKBOX | BS_OWNERDRAW, 150, 100, 60, 20, hWnd, (HMENU)ID_CHECK, (HINSTANCE)GetWindowLong(hWnd, GWLP_HINSTANCE), NULL);
 case WM_CTLCOLORBTN:
{
    return (INT_PTR)CreateSolidBrush(RGB(0, 0, 0));
    break;
}
case WM_DRAWITEM:
{
    LPDRAWITEMSTRUCT pDIS = (LPDRAWITEMSTRUCT)lParam;
    if (pDIS->hwndItem == check)
    {
        SetTextColor(pDIS->hDC, RGB(255, 255, 255));
        SetBkColor(pDIS->hDC, RGB(0, 0, 0));
        WCHAR Text[99];
        int len = SendMessage(check, WM_GETTEXT,
            ARRAYSIZE(Text), (LPARAM)Text);
        TextOut(pDIS->hDC, pDIS->rcItem.left, pDIS->rcItem.top, Text, len);
    }
    return TRUE;
}

调试结果:

debug result

您会发现它与您的想法不同。

  

根据MSDN,创建一个所有者绘制的按钮。所有者窗口   当按钮的视觉外观已达到时,会收到WM_DRAWITEM消息   改变了。请勿将BS_OWNERDRAW样式与任何其他按钮组合使用   样式。

所以,我建议你这样做。

check = CreateWindowEx(0,L"BUTTON",L"text123", WS_CHILD | WS_VISIBLE | BS_CHECKBOX ,150, 100, 60, 20, hWnd, (HMENU)ID_CHECK, (HINSTANCE)GetWindowLong(hWnd, GWLP_HINSTANCE), NULL);
case WM_CTLCOLORSTATIC:
{
    HDC hdc = (HDC)wParam;
    HWND hWnd = (HWND)lParam;
    if (hWnd == check)
    {
        SetBkMode(hdc, TRANSPARENT);
        SetTextColor(hdc, RGB(255, 255, 255));
        return (INT_PTR)CreateSolidBrush(RGB(0, 0, 0));
    }
break;
}

通过触发WM_CTLCOLORSTATIC,文本和背景色是自绘的。

Debug result

答案 1 :(得分:0)

简单答案不适用于按钮。似乎它仅适用于文本框和复选框。 顺便说一句,这里仍然是边界。

您应该以这种方式创建按钮:

#include <CommCtrl.h>
#pragma comment(lib,"comctl32.lib")
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

 CreateWindowEx(WS_EX_TRANSPARENT, "Button", NULL, WS_CHILD | WS_VISIBLE | BS_FLAT | BS_OWNERDRAW, start_x, start_y, size_y, size_x, hWnd, (HMENU)(i + 2000), NULL, NULL);

case WM_DRAWITEM: {
            auto id = LOWORD(wParam);
            if (id >= 2000) {
                id -= 2000;
                drawButton(dis, id);
                return true;
            }


case WM_INITDIALOG: {
    INITCOMMONCONTROLSEX icx;
    icx.dwSize = sizeof(INITCOMMONCONTROLSEX);
    icx.dwICC = ICC_STANDARD_CLASSES;
    InitCommonControlsEx(&icx);