且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法只允许现有 win 应用程序的一个实例?

更新时间:2023-11-22 19:19:52

您可以创建一个 命名互斥.在应用程序启动时,通常是 WinMain() 函数,如果您成功获得互斥锁,则意味着该实例是第一个实例,否则您可以标记错误或使用其他方式激活第一个应用程序.

You can create a named mutex. At the start of the application, typically the WinMain() function, if you succeed in having the mutex, it implies the instance is the first one else you can flag an error or activate the first application using other means.

HANDLE hMutex = CreateMutex(NULL, FALSE, "MY_MUTEX_123_UNIQUE_STRING");
if (ERROR_ALREADY_EXISTS == GetLastError())
    std::cout<<"This is not the first instance\n";
else
    std::cout<<"This is first instance\n";