The first thing to begin with, is
showing a window. First, you need to include the necessary header files. We use
the #define to tell the Windows headers we are a simple win32 app, and not
include any MFC stuff:
#define WIN32_MEAN_AND_LEAN
#include <windows.h>
#include <windowsx.h>
Now we define some global
tags/constants, like the window class string(used for identifying this window),
its title(caption) and size(in pixels):
#define WINDOWS_CLASS "Tutorial0WindowClass"
#define WINDOWS_CAPTION
"Tutorial #0"
const int SCREEN_X = 640;
const int SCREEN_Y = 480;
Now we define the window
procedure. Windows passes messages to our app by using this function, and it is
the ‘heart’ of any windows application. This must be implemented in order to
behave correctly within the Windows OS, and to ‘gracefully’ finish:
LRESULT WINAPI MsgProc( HWND hwnd, UINT msg, WPARAM
wparam, LPARAM lparam )
{
switch( msg )
{
case WM_PAINT:
{
//
Simply clear the window to white, and display a message centered
RECT
rect;
PAINTSTRUCT
ps;
HDC
hdc = BeginPaint( hwnd, &ps );
GetClientRect(
hwnd, &rect );
FillRect(
hdc, &rect, CreateSolidBrush( 0x00ffffff ) );
SetTextColor(
hdc, 0 );
::DrawText(
hdc, "Basic Window", -1, &rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE );
EndPaint(
hwnd, &ps );
return 0;
}
case WM_DESTROY:
{
PostQuitMessage(
0 );
return 0;
}
}
return DefWindowProc(
hwnd, msg, wparam, lparam );
}
Finally, the entry point for the
application. This is the same as a ‘main’ in a general C application. This is
called first by windows when launching the executable. Then, by registering the
window class, we set the above window procedure as the function that will be
called by Windows. Then we create a window, and that starts calling the window
procedure. We finish with loop that processes any messages sent from Windows to
the application. Lastly, we unregister the window class:
// Main Win32 Entry Point
int WINAPI WinMain( HINSTANCE
hInst, HINSTANCE, LPSTR, INT )
{
// Register the window class
WNDCLASSEX
wc = { sizeof( WNDCLASSEX ), CS_OWNDC, MsgProc, 0, 0, GetModuleHandle(
NULL ), NULL, NULL,
NULL,
NULL, WINDOWS_CLASS, NULL };
RegisterClassEx(
&wc );
// Create the application's window
HWND
hWnd = CreateWindow( WINDOWS_CLASS, WINDOWS_CAPTION, WS_CAPTION |
WS_POPUPWINDOW | WS_VISIBLE |
S_CLIPSIBLINGS |
WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, SCREEN_X, SCREEN_Y,
GetDesktopWindow(), NULL,
wc.hInstance, NULL );
// Show the window
ShowWindow(
hWnd, SW_SHOWDEFAULT );
UpdateWindow(
hWnd );
// Enter the message loop
MSG
msg;
ZeroMemory(
&msg, sizeof( msg ) );
// Process all messages
while( msg.message !=
WM_QUIT )
{
if( PeekMessage( &msg, NULL,
0U, 0U, PM_REMOVE ) )
{
TranslateMessage(
&msg );
DispatchMessage(
&msg );
}
}
// Unregister the class
UnregisterClass(
WINDOWS_CLASS, wc.hInstance );
return 0;
}
Here are the links to the source and the executable.