Forcing Only One Instance of an Application to Run at a Time in Visual C++
Posted
by Simon Soosai
on January 14th, 2003
#pragma comment(linker, "/SECTION:.shr,RWS")
#pragma data_seg(".shr")
HWND g_hWnd = NULL;
#pragma data_seg()
On the App::InitInstance() add the code below:
//For single instance checking if (g_hWnd) { ::SetForegroundWindow(g_hWnd); if (IsIconic(g_hWnd)) ::ShowWindow(g_hWnd, SW_RESTORE); // terminates the creation }
After Creating the Main Frame, get the handle and store it on the shared variable below.
g_hWnd = m_pMainWnd->m_hWnd;

Comments
how could i use this in SDI
Posted by Legacy on 03/03/2003 12:00amOriginally posted by: Winch Fang
?_?
ReplyCode Update using CreateMutex
Posted by Legacy on 01/17/2003 12:00amOriginally posted by: Simon Soosai
ReplyIs it thread safe & high security?
Posted by Legacy on 01/15/2003 12:00amOriginally posted by: Minh Tuan
The code is nice but I think there are 2 problems:
Reply1. Should we use the InterlockedExchange function to get/set the window handle? Because this function is thread & process safe.
2. I think it's not suitable for Window Services because other untrusted applications can modify our shared variable. For example, they may terminate or forbit our application to start.
Easiest != Safest
Posted by Legacy on 01/15/2003 12:00amOriginally posted by: Blake Miller
"This document is the easist way to check for multiple instances and bring the first instance on to the focus"
ReplyHe makes no claims that it is the safest or most reliable...
Good article,thanks.
Posted by Legacy on 01/14/2003 12:00amOriginally posted by: Artem
And by the way, thank you very much for discovering to
Replyme - what is the 'beast' - "pragma <....>".
Good luck,man!
Not thread safe, use mutex instead
Posted by Legacy on 01/14/2003 12:00amOriginally posted by: Brian Friesen
If you need to solve the problem of a single instance application, please use one of the mutex based solutions. It's the only way to guarantee it is thread-safe.
Reply