【发布时间】:2013-09-10 19:09:25
【问题描述】:
我正在尝试创建一个简单的窗口,但我遇到了一些问题。编译器不会给出错误,但它根本无法创建窗口的 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;
}
【问题讨论】:
-
你为什么使用 PeekMessage 而不是 GetMessage?警告的原因是您在 msg 初始化之前检查 msg.message。
-
因为,我想写一个 DirectX 应用程序。而在 DirectX 应用程序(如游戏等)中,程序员建议使用 PeekMessage,而不是 GetMessage。我想尝试编译代码,但是当我编译它时,我不会创建一个窗口。我因此感到不舒服,并将问题写在这里。也许 PeekMessage 仅在我编写 DirectX 渲染、初始化代码等时才有效。而且我不知道什么时候初始化 msg。我怎么知道?
-
你可以知道
msg没有初始化,因为在代码中很明显是这样。在将任何内容分配给msg.message之前,您会测试msg.message的值。