Windows客户端开发--只允许有一个实例运行

时间:2022-08-29 19:30:43
没有人会漫无目的地旅行,那些迷路者是希望迷路。
--------《岛上书店》

一个pc可以同时运行几个qq,但是只允许运行一个微信。

所以,今天就跟大家分享一下,如何确保你开发的windows客户端只能同时运行一个实例,或是叫进程。

使用mutex
OpenMutex函数为现有的一个已命名互斥体对象创建一个新句柄。
即在main函数中创建一个互斥量:

WINAPI WinMain(
HINSTANCE, HINSTANCE, LPSTR, int)
{
try {
// Try to open the mutex.
HANDLE hMutex = OpenMutex(
MUTEX_ALL_ACCESS, 0, "MyApp1.0");

if (!hMutex)
// Mutex doesn’t exist. This is
// the first instance so create
// the mutex.
hMutex = a
CreateMutex(0, 0, "MyApp1.0");
else
// The mutex exists so this is the
// the second instance so return.
return 0;

Application->Initialize();
Application->CreateForm(
__classid(TForm1), &Form1);
Application->Run();

// The app is closing so release
// the mutex.
ReleaseMutex(hMutex);
}
catch (Exception &exception) {
Application->
ShowException(&exception);
}
return 0;
}

使用CreateEvent
CreateEvent是一个Windows API函数。它用来创建或打开一个命名的或无名的事件对象。

bool CheckOneInstance()
{

HANDLE m_hStartEvent = CreateEventW( NULL, FALSE, FALSE, L"Global\\CSAPP" );

if(m_hStartEvent == NULL)
{
CloseHandle( m_hStartEvent );
return false;
}


if ( GetLastError() == ERROR_ALREADY_EXISTS ) {

CloseHandle( m_hStartEvent );
m_hStartEvent = NULL;
// already exist
// send message from here to existing copy of the application
return false;
}
// the only instance, start in a usual way
return true;
}

使用FindWindow
FindWindow这个函数检索处理*窗口的类名和窗口名称匹配指定的字符串。

HWND hWnd = ::FindWindow(LPCTSTR lpClassName, LPCTSTR lpWindowName);
if (hWnd != null)
{
ShowWindow(hWnd, SW_NORMAL);
return (1);
}

使用CreateSemaphore
创建一个新的信号量

CreateSemaphore(NULL, TRUE, TRUE, "MYSEMAPHORE");
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
return FALSE
}