Not only can you run more than one application at a time with Windows, you can also run more than one copy, or instance, of the same application at a time. To distinguish one instance from another, Windows supplies a unique instance handle (a unique integer identifying the instance) each time it calls the WinMain function to start the application.
With some multitasking systems, to run multiple instances of the same application at the same time the system loads a fresh copy of the application's code and data into memory and runs that copy. With Windows, when a new instance of the application is started only the data for the application is loaded. Windows uses the same code for all instances of the application. This saves as much space as possible for other applications and for data. However, this method requires that the code segments of the application remain unchanged while the application is running. This means that you must not store data in a code segment or change the code while the application is running.
For most Windows applications, the first instance has a special role. Many of the resources an application creates, such as window classes, are generally available to all applications. Consequently, only the first instance of an application creates these resources. All subsequent instances may use the resources without having to create them. To determine which is the first instance, Windows sets the hinstPrevious parameter of WinMain to NULL if there are no previous instances. The following example shows how to check that a previous instance does not exist:
int PASCAL WinMain(hinstCurrent, hinstPrevious, lpszCmdLine, nCmdShow)
HINSTANCE hinstCurrent; /* handle of current instance */
HINSTANCE hinstPrevious; /* handle of previous instance */
LPSTR lpszCmdLine; /* address of command line */
int nCmdShow; /* show-window type (open/icon) */
{
if (hinstPrevious == NULL)
.
.
.
}
To keep the user from starting more than one instance of your application, the application should check the hinstPrevious parameter upon starting and should return to Windows if the parameter is not NULL. The following example shows how to do this:
if (hinstPrevious)
return NULL;