Not only can you run more than one application at a time in 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” each time it calls the WinMain function to start the application. An instance is a separately executing copy of an application, and an instance handle is an integer that uniquely identifies an instance.
Summary: Windows shares code among multiple instances of an application.
In some multitasking systems, if you run multiple instances of the same application, the system loads a fresh copy of the application's code and data into memory and executes it. In Windows, when you start a new instance of the application, 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 your application remain unchanged for the duration of the application. This means that you must not store data in a code segment or change the code while the program 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 creating them. To let you determine which is the first instance, Windows sets the hPrevInstance parameter of WinMain to NULL if there are no previous instances. The following example shows how to check that previous instance does not exist:
int PASCAL WinMain( hInstance, hPrevInstance, lpCmdLine, nCmdShow )
HANDLE hInstance;/* current instance*/
HANDLE hPrevInstance;/* previous instance*/
LPSTR lpCmdLine;/* command line */
int nCmdShow;/* whether to show window or icon */
{
if( !hPrevInstance )
.
.
.
}
To keep the user from starting more than one instance of your application, check the hPrevInstance parameter when the application starts; return to Windows immediately if the parameter is not NULL. The following example shows how to do this:
if( hPrevInstance )
return( NULL );