Error 1813 when calling CreateWindow() func WinApi

随声附和 提交于 2019-12-25 04:33:40

问题


I'm new in C++ and WinApi. I can't create a simple window in WinApi. CreateWindow() function returns null. GetLastError() func returns error 1813. But before creating window GetLastError() returns 0. Sorry for my English. Here is my full code:

#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;
}

回答1:


First of all, your error handling is wrong. The documentation tells you to call GetLastError only if CreateWindow failed. And CreateWindow failure is indicated by a return value of NULL. You must check the return value of CreateWindow before calling GetLastError. Please make sure you read the documentation carefully.

You make the exact same mistake in your call to RegisterClass. In your defence, this is the most common mistake made by novice Win32 programmers.

Error code 1813, is ERROR_RESOURCE_TYPE_NOT_FOUND. The documentation says:

The specified resource type cannot be found in the image file.

Again, you can learn this information by reading the documentation, once you know where to look.

What this means is that CreateWindow is trying to find a resource that is not present in the file. Perhaps you did not manage to link a menu resource.

Your window procedure is also defective. It should be:

LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    return DefWindowProc(hWnd, Msg, wParam, lParam);
}

When you start to add bespoke handling for certain messages, ensure that you still call DefWindowProc for any other messages.




回答2:


You need to return the result of DefWindowProc for messages you don't handle yourself.
See here for more information.



来源:https://stackoverflow.com/questions/29891741/error-1813-when-calling-createwindow-func-winapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!