Allowing Only One Application Instance on Win32sLast reviewed: January 3, 1997Article ID: Q124134 |
The information in this article applies to:
SUMMARYThe entry point for both Windows-based and Win32-based applications is:
int WinMain( hInstance, hPrevInstance, lpszCmdLine, nCmdShow ) HINSTANCE hInstance; /* Handle of current instance */ HINSTANCE hPrevInstance; /* Handle of previous instance */ LPSTR lpszCmdLine; /* Address of command line */ int nCmdShow; /* Show state of window */You can allow only one instance of your Windows-based application to run at a time by using hPrevInstance to determine if there is already an existing application instance; then exit the process if there is one. If there is no previous instance, hPrevInstance is NULL. However, in a Win32-based application, hPrevInstance is always NULL. Therefore, you cannot determine if another instance of your application has been started simply by examining hPrevInstance. This article gives you a method you can use.
MORE INFORMATIONUse one of the following four methods to determine if there is an existing application instance on Win32s:
Using a File MappingUsing a file mapping works well on any Win32 platform. The global atom is a cheaper resource, whereas a file mapping will cost a page of memory. A private message is good if you want to inform the first instance that the user attempted to start a second instance, and then let it handle the request -- post a message, become the active application, and so on. NOTE: You need to clean up before terminating the second instance. FindWindow() doesn't require cleanup, but this method will not work as reliably in a preemptive multitasking environment, such as Windows NT, because you can get in a race condition. The following code fragment demonstrates how a file mapping can be used to allow only one instance of a Win32-based application. This code should avoid any race conditions. Place this code at the beginning of WinMain(). The code creates a file mapping named MyTestMap using CreateFileMapping(). If MyTestMap already exists, then you know that there is already a running instance of this application. A similar technique would be used with a global atom.
Sample Code
HANDLE hMapping; hMapping = CreateFileMapping( (HANDLE) 0xffffffff, NULL, PAGE_READONLY, 0, 32, "MyTestMap" ); if( hMapping ) { if( GetLastError() == ERROR_ALREADY_EXISTS ) { // // Display something that tells the user // the app is already running. // MessageBox( NULL, "Application is running.", "Test", MB_OK ); ExitProcess(1); } } else { // // Some other error; handle error. // MessageBox( NULL, "Error creating mapping", "Test", MB_OK ); ExitProcess(1); } |
KBCategory: kbprg kbcode
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |