When I create a window in C using the CreateWindow()
function, it works fine it just disappears instantly, so I used the getch()
function to try to resolve the issue but it does not work. The window does not display the button, and crashes.
But when I used MessageBox()
instead of getch()
, it stays and functions normally. I am trying to figure out why this happens.
I tried many things, like using MessageBox()
and getch()
together, using getch()
before and after ShowWindow()
, but every time it gives me some interesting result but not the normal functionality of the window.
Code that works:
#include <windows.h>
int _stdcall WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
HWND h;
HINSTANCE i;
h = CreateWindow("Button", "XYZ", WS_OVERLAPPEDWINDOW, 15, 20, 250, 200, 0, 0, i, 0);
ShowWindow(h, nCmdShow);
MessageBox(0, "Stop", "Wait", MB_OK);
return 0;
}
Code that does not work:
#include <windows.h>
int _stdcall WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
HWND h;
HINSTANCE i;
h = CreateWindow("Button", "XYZ", WS_OVERLAPPEDWINDOW, 15, 20, 250, 200, 0, 0, i, 0);
ShowWindow(h, nCmdShow);
getch();
return 0;
}
I want to know the reason for this error. I think it is because getch()
is a DOS function, but still the compiler should at least show a warning.
There is no crash in this code.
Your getch()
example simply lacks a message loop needed to service the window, and also getch()
is meaningless in a non-console app. So your WinMain()
exits immediately after showing the button window.
Whereas your MessageBox()
example has a message loop (inside of MessageBox()
itself) which keeps WinMain()
running, and the button window processong UI messages, until the MessageBox
dialog is closed.
Also, it doesn't make sense to try to display a button as its own overlapped window. You should be registering and creating a separate overlapped window that then creates the button as a child. User actions on the button are sent to the button's parent window, so you need to create a parent window for it.