Identifying a Previous Instance of an Application

Last reviewed: November 2, 1995
Article ID: Q106385
The information in this article applies to:
  • Microsoft Win32 Application Programming Interface (API) included with:

        - Microsoft Windows NT versions 3.5 and 3.51
        - Microsoft Windows 95 version 4.0
    

SUMMARY

The entry point of both Windows and Windows NT applications is documented to be:

   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            */

However, under Windows NT, hPrevInstance is documented to always be NULL. The reason is that each application runs in its own address space and may have the same ID as another application.

To determine whether another instance of the application is running, use a named mutex. If opening the mutex fails, then there are no other instances of the application running. FindWindow() can be used with the class and window name. However, note that a second instance of the application could be started, and could execute the FindWindow() call before the first instance has created its window. Use a named object to ensure that this does not happen.

MORE INFORMATION

The fact that hPrevInstance is set to NULL simplifies porting Win16 applications. Most 16-bit Windows-based applications contain the following logic:

   if( !hPrevInstance )
      if( !InitApplication(hInstance) )
         return FALSE;

Under Windows, window classes only are registered by the first instance of an application. Consequently, if hPrevInstance is not NULL, then the window classes have already been registered and InitApplication() is not called.

Under Windows NT, because hPrevInstance is always NULL, InitApplication() is always called, and each instance of an application will correctly register its window classes.


Additional reference words: 3.10 3.50 3.51 4.00 95
KBCategory: kbui
KBSubcategory: UsrMisc



THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: November 2, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.