Most applications use two locally defined initialization functions:
The main initialization function carries out work that only needs to be done once for all instances of the application (for example, registering window classes).
The instance initialization function performs tasks that must be done for every instance of the application.
Using initialization functions helps to keep the WinMain function simple and readable; it also organizes initialization tasks so that they can be placed in a separate code segment and discarded after use. The Generic application does not discard its initialization functions. (In Chapter 26, “Memory Management,” you will encounter a sample application, Memory, that does discard its initialization functions.)
The Generic application's main initialization function looks like the following:
BOOL InitApplication(hInstance)
HANDLE hInstance; /* current instance */
{
WNDCLASS wc;
/* Fill in window class structure with parameters that describe the */
/* main window. */
wc.style = NULL; /* Class style(s). */
wc.lpfnWndProc = MainWndProc; /* Function to retrieve messages for */
/* windows of this class. */
wc.cbClsExtra = 0; /* No per-class extra data. */
wc.cbWndExtra = 0; /* No per-window extra data. */
wc.hInstance = hInstance; /* Application that owns the class. */
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = “GenericMenu”; /* Name of menu resource in .RC file. */
wc.lpszClassName = “GenericWClass”; /* Name used in call to CreateWindow. */
/* Register the window class and return success/failure code. */
return (RegisterClass(&wc));
}
Generic's instance initialization function looks like the following:
BOOL InitInstance(hInstance, nCmdShow)
HANDLE hInstance; /* Current instance identifier. */
int nCmdShow; /* Param for first ShowWindow() call. */
{
HWND hWnd; /* Main window handle. */
/* Save the instance handle in static variable, which will be used in */
/* many subsequence calls from this application to Windows. */
hInst = hInstance;
/* Create a main window for this application instance. */
hWnd = CreateWindow(
“GenericWClass”, /* See RegisterClass() call. */
“Generic Sample Application”, /* Text for window title bar. */
WS_OVERLAPPEDWINDOW, /* Window style. */
CW_USEDEFAULT, /* Default horizontal position. */
CW_USEDEFAULT, /* Default vertical position. */
CW_USEDEFAULT, /* Default width. */
CW_USEDEFAULT, /* Default height. */
NULL, /* Overlapped windows have no parent. */
NULL, /* Use the window class menu. */
hInstance, /* This instance owns this window. */
NULL /* Pointer not needed. */
);
/* If window could not be created, return “failure” */
if (!hWnd)
return (FALSE);
/* Make the window visible; update its client area; and return “success” */
ShowWindow(hWnd, nCmdShow); /* Show the window */
UpdateWindow(hWnd); /* Sends WM_PAINT message */
return (TRUE);
}