Determining If a Previous Instance of a Process Is Running

< BACK  NEXT >
[oR]

Makers of certain target devices, such as Pocket PC, recommend that only a single instance of your application run at any time. In the event the user attempts to start a second instance, the second instance should terminate and bring the first instance to the foreground. The code in Listing 5.6 shows how to use FindWindow to locate the main application window of the first instance. The function FindWindow is passed the class name of the window. The second parameter is the window title, which is passed as NULL so that any window title will result in a match.

If FindWindow returns NULL, then this is the first instance of the application, and the application can continue executing. A non-NULL value means that another instance is running, so the current instance calls ShowWindow (to ensure the main application window of the first instance is not hidden) and SetForegroundWindow (to bring the main application window of the first instance to the foreground). This activates the thread and gives the window the input focus. Finally, the current instance terminates itself by calling PostQuitMessage. This code would be executed as soon as the application starts, and before any windows have been created.

Listing 5.6 Handles second instances of an application
 BOOL Listing5_6() {   HWND hWnd;   hWnd = FindWindow(_T("EXAMPLES"), NULL);   if(hWnd == NULL)     return FALSE; // this is the first instance   ShowWindow(hWnd, SW_SHOWNORMAL);   SetForegroundWindow(hWnd);   PostQuitMessage(0); // terminate this instance   return TRUE; } 

The second instance may need to pass information to the first instance, for example, specifying a document to open. This requires some form of interprocess communication. The simplest approach is for the second instance to send a message containing the data to the first instance. Alternatively, more sophisticated interprocess communication techniques can be used, such as memory-mapped files. This requires that access to the shared memory be synchronized, which is covered in the next chapter.


< BACK  NEXT >


Windows CE 3. 0 Application Programming
Windows CE 3.0: Application Programming (Prentice Hall Series on Microsoft Technologies)
ISBN: 0130255920
EAN: 2147483647
Year: 2002
Pages: 181

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net