1

我有这样的代码:

In WM_CREATE

    hCheckBox = CreateWindowEx(0,"Button","Random text", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS| BS_AUTOCHECKBOX | BS_TEXT | WS_GROUP | WS_TABSTOP,150,323,300,20,hwnd,0,hInstance,0) ;


In WM_COMMAND

    if ( SendMessage( hCheckBox , BM_GETCHECK, (WPARAM) NULL, (LPARAM) NULL ) == BST_CHECKED )
        MessageBox( 0, "Working", "Msg", 0 );

不管复选框是否被选中,它永远不会返回 BST_CHECKED。试图让它在最后 2 小时内工作:(

4

1 回答 1

6

是否hCheckBox是局部自动变量并不完全清楚。CreateWindow如果是这样,我可以向您保证,从触发到收到 WM_COMMAND 消息,它不会保持其值。改用这个:

LRESULT chk = SendDlgItemMessage(hDlg, IDC_CHECKBOX_CTRL_ID, BM_GETCHECK, 0, 0);

hDlg您的对话框或主窗口句柄在哪里,并且IDC_CHECKBOX_CTRL_ID是控件 ID。为此,您需要将控件 ID 指定为创建调用的 HMENU 参数的非零值:

hCheckBox = CreateWindowEx(0,"Button","Random text", WS_CHILD | WS_VISIBLE | 
    WS_CLIPSIBLINGS| BS_AUTOCHECKBOX | BS_TEXT | WS_GROUP |
    WS_TABSTOP,150,323,300,20,hwnd, IDC_CHECKBOX_CTRL_ID, hInstance,0);

如果它不明显。将 IDC_CHECKBOX_CTRL_ID 定义为非零整数。


编辑

假设控件设置正确,您应该能够在 WndProc 中为该复选框处理 WM_COMMAND,如下所示

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    switch (message)
    {
    case WM_CREATE:
        CreateWindowExA(0,"Button","Random text", WS_CHILD | WS_VISIBLE | 
            WS_CLIPSIBLINGS| BS_AUTOCHECKBOX | BS_TEXT | WS_GROUP |
            WS_TABSTOP,100,100,300,48, hWnd, (HMENU)IDC_CHECKBOX_CTRL_ID, hInst, 0);
        break;

    case WM_COMMAND:
        wmId = LOWORD(wParam);
        wmEvent = HIWORD(wParam);

        // Parse the menu selections:
        if (wmId == IDC_CHECKBOX_CTRL_ID)
        {
            if (wmEvent == BN_CLICKED)
            {
                LRESULT chkState = SendMessage((HWND)lParam, BM_GETCHECK, 0, 0);
                if (chkState == BST_CHECKED)
                    MessageBoxA(hWnd, "Checkbox is checked!", "CheckBox", MB_OK);
            }
            break;
        };
        // fall-thru intentional

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    };

    return 0;
}

我只是把它撞到一个带有空白窗口的普通 WIN32 应用程序中。结果如下图所示:

勾选复选框的结果

于 2012-11-27T21:52:17.473 回答