Search code examples
c++winapicreatewindow

Error 1813 when calling CreateWindow() func WinApi


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

Solution

  • 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.