HomeC&C++WainTutorialsSamplesTip&TrickTools


This tutorial will start with a very simple application with a empty window, at the end we have created a complete drawing application.
First the base window, it does not do anything, but we will use it as base for other the applications.
First a function to create the window:
HWND CreateMainWindow()
{
   WNDCLASS wc;
   memset(&wc, 0, sizeof(WNDCLASS));
   wc.style = CS_HREDRAW | CS_VREDRAW  | CS_DBLCLKS ;
   wc.lpfnWndProc = (WNDPROC )MainWndProc;
   wc.hInstance = InstanceHandle;
   wc.hbrBackground = (HBRUSH )(COLOR_WINDOW + 1);
   wc.lpszClassName = "SimpleWinWndClass";
   wc.lpszMenuName = 0;
   wc.hCursor = LoadCursor(NULL, IDC_ARROW);
   wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
   if(!RegisterClass(&wc))
      return 0;

   return CreateWindow("SimpleWinWndClass",
                       "Simple-Window",
                       WS_MINIMIZEBOX | WS_VISIBLE |
                       WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
                       WS_MAXIMIZEBOX | WS_CAPTION |
                       WS_BORDER | WS_SYSMENU | WS_THICKFRAME,
                       CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
                       0,
                       0,
                       InstanceHandle,
                       0);
}
First we create the Windows class, the we create the window. We use CW_USEDEFAULT to create the window with the default size. "Simple-Window" is the title of the window, "SimpleWinWndClass" is the name of the Window-Class.
MainWndProc is the name of the WindowProc, the function which receives all messages for our window. It could look like this:
LRESULT CALLBACK MainWndProc(HWND hwnd,
                             UINT msg,
                             WPARAM wParam,
                             LPARAM lParam)
{
  switch (msg)
  {
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    default:
      return DefWindowProc(hwnd,msg,wParam,lParam);
  }
  return 0;
}
We let the default window proc handle most of the messages, we just makes sure that the applikation can be closed.
The WinMain must create the Window, and run the message-loop:
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   INT nCmdShow)
{
   InstanceHandle = hInstance;

   if((MainWindow = CreateMainWindow()) == (HWND )0)
   {
      MessageBox(0,
                 "Failed to create MainWindow!",
                 "Warning",
                 MB_OK);
      return 0;
   }
   ShowWindow(MainWindow, SW_SHOW);
   MSG Msg;
   while(GetMessage(&Msg, 0, 0, 0))
   {
      TranslateMessage(&Msg);
      DispatchMessage(&Msg);
   }
   return Msg.wParam;
}
Now we just need two globale variables, and a include, and we are done:
#include <windows.h>
HINSTANCE InstanceHandle;
HWND      MainWindow;
The complete code for the application can be found here