c++ - 无法创建 HWND

标签 c++ winapi hwnd

我正在尝试创建一个简单的窗口,但我遇到了一些问题。编译器不会报错,但它根本无法创建窗口的 hWnd。它还表示正在使用“msg”变量而未初始化。这不是错误,只是警告,但是我感到不舒服。当我单击调试屏幕中的 hWnd 表时,它显示“未使用的 CXX0030:错误:无法计算表达式”。这是代码:

#include <windows.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hWnd;
    MSG msg;

    WNDCLASSEX wcex;
    ZeroMemory(&wcex, sizeof(WNDCLASSEX));

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = "Breakout_Test";
    wcex.hIconSm = NULL;

    if(!RegisterClassEx(&wcex))
        return 0;

    hWnd = CreateWindowEx(NULL, "Breakout_Test", "Breakout Test (DirectX 9)", WS_OVERLAPPEDWINDOW, 
                            0, 0, 640, 480, NULL, NULL, hInstance, NULL);

    ShowWindow(hWnd, nCmdShow);

    while(msg.message != WM_QUIT)
    {
        if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {

        }
    }

    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
    case WM_CLOSE:
        PostQuitMessage(0);
        break;
    default:
        DefWindowProc(hWnd, message, wParam, lParam);
    }

    return 0;
}

最佳答案

你的消息循环全错了。编译器非常正确,您没有初始化 msg。我不确定你从哪里得到那个消息循环。这是标准的:

while (GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

如果你想使用一个非阻塞的基于 PeekMessage 的循环,它似乎在 DirectX 应用程序中很流行,它可能看起来像这样:

PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
while (msg.message != WM_QUIT) 
{
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        // game code here
    }
}

请注意,我们在进入测试 msg.messagewhile 循环之前初始化了 msg

您的另一个大问题是在您的窗口过程中。您不会返回从 DefWindowProc 返回的值。 default 处理程序应如下所示:

return DefWindowProc(hWnd, message, wParam, lParam);

您损坏的窗口过程是 CreateWindowEx 失败的原因。破窗过程是 CreateWindowEx 的经典故障模式之一。

进行这两项更改,您的程序就会运行。


对于像 Remy 这样担心 GetMessage returns -1 when it fails 的人来说, Raymond Chen explains why you don't need to worry about that ,至少对于这个消息循环。

关于c++ - 无法创建 HWND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18726996/

相关文章:

c++ - 删除 C++ 中的重复模式

c++ - 为什么 c++17 的 emplace() 函数没有引用资格?

c++ - 为什么 include 指令在头文件之上?

c++ - C++ 中的任务监视器和管理器

c++ - 如何在 C++ 中获取进程名称

c++ - 继承,使基成员变量为const

.net - 如何使用 .Net 直接读取磁盘?

c# - 在 C# 中获取 Outlook 事件窗口句柄 hwnd

wpf - GDI 渲染到 WPF 窗口