-
A simple window
Hi guys, I know this is pathetic, but I was having trouble when I tried to use CreateWindowEx(). Although I did it before, I kept getting "Window creation failed" error box I used to error check.
Code:
#include "stdafx.h"
#include "Resource.h"
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CREATE:
{
HMENU hMenu, hSubMenu;
hMenu = CreateMenu();
hSubMenu = CreateMenu();
AppendMenu(hSubMenu, MF_STRING, 9001, "E&xit");
AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&File");
hSubMenu = CreateMenu();
AppendMenu(hSubMenu, MF_STRING, 9002, "Greetings");
AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&Hi");
SetMenu(hwnd, hMenu);
}
break;
case WM_COMMAND:
switch(LOWORD(wParam))
{
case 9001:
SendMessage(hwnd, WM_CLOSE, 0, 0);
break;
case 9002:
MessageBox(NULL, "Greetings", "Hi there", MB_OK);
break;
}
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
DefWindowProc(hwnd, msg, wParam, lParam);
break;
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShowCmd)
{
HWND hwnd;
MSG msg;
WNDCLASSEX wcex;
const char g_szClassName[] = "Window Class Name";
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hbrBackground = (HBRUSH) (COLOR_HIGHLIGHTTEXT +1);
wcex.hCursor = LoadCursor(NULL, IDC_CROSS);
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
wcex.hInstance = hInstance;
wcex.lpfnWndProc = WndProc;
wcex.lpszClassName = g_szClassName;
wcex.lpszMenuName = NULL;
wcex.style = 0;
if(!RegisterClassEx(&wcex))
{
MessageBox(NULL, "Window class registration failed", "Error", MB_OK);
return 0;
}
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, g_szClassName, "My window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 180, 120,
NULL, NULL, hInstance, NULL);
if(!hwnd)
{
MessageBox(NULL, "Window creation failed", "Error", MB_OK);
return 0;
}
ShowWindow(hwnd, nShowCmd);
UpdateWindow(hwnd);
while(GetMessage(&msg, NULL, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
Your help will be very much appreciated.
-
Maybe the class name cannot have spaces
-
Your window procedure needs to return the result of the DefWindowProc call, not break (and therefore return zero).
Also, it would be wise to replace those literal numbers in your WM_COMMAND handler with properly defined constants; those raw numbers are meaningless to everyone and anyone and, in a week - perhaps longer - they'll be meaningless to you, too.
-
Yep - if you return 0 on WM_NCCREATE, window creation fails.
gg
-
thanks for the tips, guys