我是 C++ 和 WinApi 的新手。我无法在 WinApi 中创建一个简单的窗口。 CreateWindow() 函数返回空值。 GetLastError() 函数返回错误 1813。 但是在创建窗口之前 GetLastError() 返回 0。对不起我的英语。这是我的完整代码:
#include <Windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)
{
LPCWSTR szWindowClass = TEXT("WndClass");
LPCWSTR szTitle = TEXT("Main window");
DWORD dwError;
WNDCLASS wc;
wc.style = CS_OWNDC;
wc.hInstance = hInstance;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wc.lpfnWndProc = WndProc;
wc.lpszClassName = szWindowClass;
wc.lpszMenuName = L"MenuName";
dwError = GetLastError(); //0
RegisterClass(&wc);
dwError = GetLastError();//0
HWND hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);//NULL
dwError = GetLastError();//1813 =(
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
return 0;
}
最佳答案
首先,你的错误处理是错误的。文档告诉您仅当 CreateWindow
失败时才调用 GetLastError
。 CreateWindow
失败由返回值 NULL
指示。在调用 GetLastError
之前,您必须检查 CreateWindow
的返回值。请确保您阅读了 documentation仔细。
您在调用 RegisterClass
时犯了完全相同的错误。为您辩护,这是新手 Win32 程序员最常犯的错误。
错误代码 1813,是 ERROR_RESOURCE_TYPE_NOT_FOUND
。 documentation说:
The specified resource type cannot be found in the image file.
同样,您可以通过阅读文档来了解这些信息,一旦您知道在哪里查看。
这意味着 CreateWindow
正在尝试查找文件中不存在的资源。也许您没有设法链接菜单资源。
您的窗口过程也有缺陷。应该是:
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
当您开始为某些消息添加定制处理时,请确保您仍然为任何其他消息调用 DefWindowProc
。
关于c++ - 调用 CreateWindow() func WinApi 时出现错误 1813,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891741/