注册 登录
编程论坛 C语言论坛

C语言WM_COMMAND接收不到控件消息,只显示窗口不显示对话框?

himdonkin 发布于 2023-04-19 17:29, 119 次点击
#include<windows.h>
#include<stdio.h>
#include"resource.h"
static HINSTANCE hInst;
BOOL CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INITDIALOG:
        return TRUE;
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDOK:
        case IDCANCEL:
            EndDialog(hDlg, 0);
            return TRUE;
        }
        break;
    }
    return FALSE;
}
void Dialog(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
   
    switch (LOWORD(wParam))
    {
    case IDD_DIALOG1:
        DialogBox(hInst, (char*)IDD_DIALOG1, hWnd, DlgProc);
        
        break;
    }
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msgID, WPARAM wParam, LPARAM lParam)
{
   
    switch (msgID)
    {
    case WM_COMMAND:
        Dialog(hWnd,msgID,wParam,lParam);
        break;
    case WM_CREATE:
        hInst = ((LPCREATESTRUCT)lParam)->hInstance;
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    }
    return DefWindowProc(hWnd, msgID, wParam, lParam);
}
int main()
{
    {
        HINSTANCE hInstance = GetModuleHandle(NULL);

        WNDCLASS wc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 3);
        wc.hCursor = NULL;
        wc.hIcon = NULL;
        wc.hInstance = hInstance;
        wc.lpfnWndProc = WndProc;
        wc.lpszClassName = "main";
        wc.lpszMenuName = NULL;
        wc.style = CS_HREDRAW | CS_VREDRAW;
        RegisterClass(&wc);
        HWND hWnd = CreateWindowEx(0, "main", "Mordem Scanning", WS_OVERLAPPEDWINDOW, 100, 100, 900, 900, NULL, NULL, hInstance, NULL);
        
        ShowWindow(hWnd, SW_SHOW);
        UpdateWindow(hWnd);
        MSG nMsg = { 0 };
        while (1)
        {
            if (PeekMessage(&nMsg, hWnd, 0, 0, PM_NOREMOVE))
            {
                if (GetMessage(&nMsg, hWnd, 0, 0))
                {
                    TranslateMessage(&nMsg);
                    DispatchMessage(&nMsg);
                }
                else
                {
                    return 0;
                }
            }
            else
            {

            }
        }
    }
}
1 回复
#2
东海ECS2023-04-19 19:20
在Dialog函数中,需要使用HIWORD函数获取控件ID,而不是LOWORD函数,因为控件ID位于wParam的高16位,而LOWORD函数只获取低16位。因此,修改Dialog函数如下:

void Dialog(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (HIWORD(wParam)) { case BN_CLICKED: switch (LOWORD(wParam)) { case IDD_DIALOG1: DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, DlgProc); break; } break; } }


此外,在DialogBox函数中,应该使用MAKEINTRESOURCE宏来转换IDD_DIALOG1为资源ID,而不是强制类型转换。修改代码如下:

DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, DlgProc);

这样就可以正常显示对话框并接收控件消息了。
1