#include <stdio.h>
#include <stdbool.h>
#include <Windows.h>
HWND WindowHandle;
HINSTANCE Instance;
const wchar_t WindowClassName[] = L"Temp Projcet";
LRESULT CALLBACK WindowProc(HWND _windowHandle, UINT _msg, WPARAM _param, LPARAM _param1) {
switch (_msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(WindowHandle, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
EndPaint(WindowHandle, &ps);
} break;
case WM_CLOSE: {
if (IDOK == MessageBoxW(WindowHandle, L"Quit?", L"My application", MB_OKCANCEL)) {
DestroyWindow(WindowHandle);
}
return false;
} break;
case WM_DESTROY: {
PostQuitMessage(0);
} break;
default:
break;
}
return DefWindowProcW(WindowHandle, _msg, _param, _param1);
}
ATOM RegisterWindowClass(void) {
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WindowProc;
wc.hInstance = Instance;
wc.lpszClassName = WindowClassName;
return RegisterClassW(&wc);
}
int APIENTRY wWinMain(HINSTANCE _instance, HINSTANCE _prevInstance, PWSTR _cmdLine, int _cmdShow) {
Instance = _instance;
RegisterWindowClass();
WindowHandle = CreateWindowExW(
0,
WindowClassName,
L"This a window",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,
NULL,
Instance,
NULL
);
DWORD err = GetLastError();
// Why error 1400 Invalid window handle?
MSG msg = { 0 };
while (GetMessageW(&msg, WindowHandle, 0, 0)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}
为什么创建窗口会返回1400个无效句柄?不应该吧?创建窗口函数里没有窗口句柄好吗?怎么会是无效句柄呢?通过搜索引擎找了半天,还是解决不了这个问题?
为什么 CreateWindowExW()
返回 1400?
第 44 行的代码。
最佳答案
您在窗口过程中使用 WindowHandle
,然后它被设置为 CreateWindowEx
的返回值。 CreateWindowEx
调用的一部分是使用 WM_NCCREATE
和 WM_CREATE
调用窗口过程。您的窗口过程调用 DefWindowProc
时带有空句柄。
此处的简单解决方案是使用 _windowHandle
参数代替全局的 WindowHandle
。
另请注意,为了让您的窗口可见,您需要调用 ShowWindow
。此外,您发布的退出消息并不特定于该窗口,因此您的 GetMessage
调用不会检索它,应用程序也不会结束。
关于c++ - 为什么错误 1400 Invalid window handle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849349/