I have a windows application. I want to allow multiple instances for a single user session but I don\'t want multiple instances from different users. Put it simple, if A log
I used previous code under win10/VS 2017 / 64 bits
It's wrong to test against if (::CreateMutex..
we must check error, so use:
BOOL checkUniqueInstance()
{
if (::CreateMutexW(NULL,
FALSE,
L"Global\\27828F4B-5FC9-40C3-9E81-6C485020538F") != NULL) {
auto err = GetLastError();
if (err == 0) {
return TRUE;
}
}
CString msg;
msg.Format(_T("err: %d - Mutex NOT acquired"), GetLastError());
OutputDebugString(msg);
// Exit application
return FALSE;
}
This requirement can be accomplished using a named Mutex Object in the global Kernel Object Namespace. A mutex object is created using the CreateMutex function. Here is a small program to illustrate its usage:
int _tmain(int argc, _TCHAR* argv[]) {
if ( ::CreateMutexW( NULL,
FALSE,
L"Global\\5BDC0675-2318-404A-96CA-DBDE9BC2F71D" ) != NULL ) {
auto const err{ GetLastError() };
std::wcout << L"Mutex acquired. GLE = " << err << std::endl;
// Continue execution
} else {
auto const err{ GetLastError() };
std::wcout << L"Mutex not acquired. GLE = " << err << std::endl;
// Exit application
}
_getch();
return 0;
}
The first application instance will create the mutex object, and GetLastError returns ERROR_SUCCESS
(0). Subsequent instances will acquire a reference to the existing mutex object, and GetLastError returns ERROR_ALREADY_EXISTS
(183). Instances started from another client session will not acquire a reference to the mutex object, and GetLastError returns ERROR_ACCESS_DENIED
(5).
A few notes on the implementation: