使用WINAPI如何更改复选框按钮的值?

时间:2014-12-02 19:28:34

标签: c++ windows winapi

目前我在WM_CREATE创建了一个复选框:

hwndButtonPollFlag = 
CreateWindow(
    TEXT("BUTTON"), 
    TEXT(sA.getMonitor(monitorSelected)->szDevice),
    WS_CHILD | WS_VISIBLE | SS_WHITERECT | BS_CHECKBOX, 
    0, 
    0, 
    0,
    0, 
    hwnd, 
    (HMENU)IDB_PollFlag, 
    hInstance, 
    NULL);

每当点击另一个按钮时,我都会尝试更改它的值:

    if (sA.getScreenArray(monitorSelected)->getPollFlag())
    {
        SetWindowLongPtr(hwndButtonPollFlag, GCL_STYLE, WS_VISIBLE | BST_CHECKED);
    }
    else
    {
        SetWindowLongPtr(hwndButtonPollFlag, GCL_STYLE, WS_VISIBLE | BST_UNCHECKED);
    }
    SetWindowText(hwndButtonPollFlag, TEXT(sA.getMonitor(monitorSelected)->szDevice));

这确实会更改复选框旁边显示的文本,但不会更改按钮的实际状态。此外,我希望复选框只有两个状态(已选中或未选中)是否有任何其他方式来创建该效果,而不是按钮返回有以下内容:

switch (HIWORD(wParam))
    {
    case BST_CHECKED:
        sA.getScreenArray(monitorSelected)->setPollFlag(true);
        return 0;
    case BST_INDETERMINATE:
        if (sA.getScreenArray(monitorSelected)->getPollFlag())
        {
            SetWindowLongPtr(hwndButtonPollFlag, GCL_STYLE, WS_VISIBLE | BST_UNCHECKED);
        }
        else
        {
            SetWindowLongPtr(hwndButtonPollFlag, GCL_STYLE, WS_VISIBLE | BST_CHECKED);
        }
        return 0;
    case BST_UNCHECKED:
        sA.getScreenArray(monitorSelected)->setPollFlag(false);
        return 0;
    }

编辑:正如Mark Ransom所说,我使用了带有BM_GETCHECK和BM_SETCHECK标志的消息:

    case IDB_MONITOR:
    monitorSelected = LOWORD(lParam);
    if (sA.getScreenArray(monitorSelected)->getPollFlag())
    {
        SendMessage(hwndButtonPollFlag, BM_SETCHECK, BST_CHECKED, NULL);
    }
    else
    {
        SendMessage(hwndButtonPollFlag, BM_SETCHECK, BST_UNCHECKED, NULL);
    }
    SetWindowText(hwndButtonPollFlag, TEXT(sA.getMonitor(monitorSelected)->szDevice));
    return 0;
case WM_COMMAND:
    //sA.getScreenArray(monitorSelected)->setPollFlag(LOWORD(lParam));
    switch (LOWORD(wParam))
    {
    case IDB_PollFlag:
        if (SendMessage(GetDlgItem(hwnd, IDB_PollFlag), BM_GETCHECK, 0, 0) == BST_CHECKED)
        {
            SendMessage(hwndButtonPollFlag, BM_SETCHECK, BST_CHECKED, NULL);
            sA.getScreenArray(monitorSelected)->setPollFlag(true);
        }
        else {
            SendMessage(hwndButtonPollFlag, BM_SETCHECK, BST_UNCHECKED, NULL);
            sA.getScreenArray(monitorSelected)->setPollFlag(false);
        }
        break;
    }
    return 0;

2 个答案:

答案 0 :(得分:5)

您需要发送BM_SETCHECK消息。

SendMessage(hwndButtonPollFlag, BM_SETCHECK, BST_CHECKED, 0);

答案 1 :(得分:3)

BST_CHECKEDBST_UNCHECKED不是窗口样式,它们只是标记CheckDlgButtonIsDlgButtonChecked API函数使用的值。 CheckDlgButton是调用以更改其状态的函数。

(或者,您可以直接向该按钮发送BM_SETCHECKBM_GETCHECK条消息,效果相同。)