gpt4 book ai didi

c++ - 无法创建 HWND

转载 作者:太空宇宙 更新时间:2023-11-04 15:04:53 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的窗口,但我遇到了一些问题。编译器不会报错,但它根本无法创建窗口的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com