HWND == NULL

Ok I really give up with this piece of code, I don't see what's wrong with it, can anyone give me any clues?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <Windows.h>
#include <string>
	using namespace std;
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hprevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	string classname = "GameClass";
	
	WNDCLASSEX wcex = {sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW , WndProc, 0, 0, hInstance, NULL, NULL, NULL, NULL, classname.c_str(), NULL};
	if(!RegisterClassEx(&wcex))
	{
		::MessageBoxA(NULL, "Failed to register class", "Error", NULL);
		return 1;
	}

	HWND hWnd;
	hWnd = CreateWindow(classname.c_str(), "Game Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, NULL, NULL, hInstance, NULL);

	if(!hWnd)
	{
//Here is where is breaks
		::MessageBoxA(NULL, "Failed to start hwnd == null", "Error", NULL);
		return 1;
	}

	ShowWindow(hWnd, SW_SHOWNORMAL);
	UpdateWindow(hWnd);

	MSG msg;
	ZeroMemory(&msg, sizeof(MSG));

	while (msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			//Game logic
		}
	}

	::UnregisterClass("GameClass", hInstance);
	return 0;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch(message)
	{
	case WM_DESTROY:
		::MessageBoxA(NULL, "Shutting down", "Bye now", NULL);
		PostQuitMessage(0);
		break;
	default:
		break;
	}
	return 0;
}
The window procedure needs to return DefWindowProc(hwnd, message, wParam, lParam) for unhandled messages. If you handle WM_DESTROY you should return 0. When you handle a message you should make sure you return a value that Windows expects.

On a side note, you should really use unicode strings instead of ascii because Windows works natively with unicode. There is a slight performance hit when you call ascii functions that take string arguments because they end up converting the strings to unicode behind the scenes and calling the unicode version of the function.
Last edited on
Thanks! Worked perfectly :D
Topic archived. No new replies allowed.