The simple windows program below creates a very basic window with a system menu icon, a minimise, maximise and close box. It can be compiled in either C or C++.


  1. #include <windows.h>
  2. LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
  3. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow)
  4. {
  5. WNDCLASSEX wc;
  6. MSG msg;
  7. //Registering the Window Class
  8. wc.cbSize = sizeof(WNDCLASSEX);
  9. wc.style = 0;
  10. wc.lpfnWndProc = WndProc;
  11. wc.cbClsExtra = 0;
  12. wc.cbWndExtra = 0;
  13. wc.hInstance = hInstance;
  14. wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  15. wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  16. wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
  17. wc.lpszMenuName = NULL;
  18. wc.lpszClassName = TEXT("myWindowClass");
  19. wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
  20. RegisterClassEx(&wc);
  21. //Creating the Window
  22. CreateWindowEx(WS_EX_CLIENTEDGE,TEXT("myWindowClass"),TEXT("Simple Window"), WS_VISIBLE | WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);
  23. //The Message Loop
  24. while(GetMessage(&msg, NULL, 0, 0) > 0)
  25. {
  26. TranslateMessage(&msg);
  27. DispatchMessage(&msg);
  28. }
  29. return msg.wParam;
  30. }
  31. //WndProc procedure. Application acts on messages
  32. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  33. {
  34. switch(msg)
  35. {
  36. case WM_CLOSE:
  37. DestroyWindow(hwnd);
  38. break;
  39. case WM_DESTROY:
  40. PostQuitMessage(0);
  41. break;
  42. default:
  43. return DefWindowProc(hwnd, msg, wParam, lParam);
  44. }
  45. return 0;
  46. }


Download


Line 1 – All windows programs must include the header file <windows.h>. This contains declarations for all of the functions in the Windows API, all the common macros used by Windows programmers, and all the data types used by the various functions and subsystems.
Line 2 – Function declaration for CALLBACK function WndProc.
Line 3 – WinMain function. Marks the program entry point.
Line 5 – Declares the wc structure variable which is used to define the Window’s class.
Line 6 – Declares the msg structure variable for holding Windows messages.
Lines 8 to 19 – Defines the Window’s class
Line 20 – Registers windows class using the function RegisterClassEx.
Line 22 – Once a window has been defined and registered it is created using the API function CreateWindowEx.
Lines 24 to 30 – The final part of WinMain is the message loop. The purpose of the message loop is to receive and process messages sent from windows. Once the message loops terminates the value of msg.wParam is returned to windows.
Line 32 to 46 – WndProc procedure. Used by windows to pass messages to an application. Is the above instance only the WM_DESTROY & WM_CLOSE message is explicitly processed.