Keywords: windows,c++, desktop app, single instance, window top
Objective: 1. Determine if an instance of this program is running. 2. If so, activate the instance that is already running (top its window) and exit the current run.
1. Use semaphore to detect if an existing instance is running (can also be used in other ways, such as mutexes, files, etc.)
1 1, _t ("single_myapp_sema")); if (G_hsinglesema && error_already_exists = = GetLastError ()) {// lookup window, activating running instance, and exits the current run }
2. Use FindWindow () to get the window handle of the running instance
HWND WINAPI FindWindow ( _in_opt_ lpctstr lpclassname, _in_opt_ lpctstr lpwindowname );
Here we already know classname, so we can use classname to find the existing window.
HWND hwnd =:: FindWindow (_t ("myappclassname"), NULL);
Then use SetForegroundWindow () to activate the running instance:
:: SetForegroundWindow (HWND);
3. When the program exits, remember to ReleaseSemaphore () and close the handle.
Reference:
1.http://xbi847ux.iteye.com/blog/1361639
2.http://blog.csdn.net/starlee/article/details/1534489
The Win app allows only a single instance to run, and the running instance window is pinned