是否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 应用程序中。结果如下图所示: