且构网

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

防止我的应用程序的多个实例

更新时间:2022-05-12 05:54:57

最常见的方法是使用互斥体,类似于以下内容:

The most common method is to use a mutex, similar to the following:

int WINAPI WinMain(...)
{
   const char szUniqueNamedMutex[] = "com_mycompany_apps_appname";
   HANDLE hHandle = CreateMutex( NULL, TRUE, szUniqueNamedMutex );
   if( ERROR_ALREADY_EXISTS == GetLastError() )
   {
      // Program already running somewhere
      return(1); // Exit program
   }

   // Program runs...

   // Upon app closing:
   ReleaseMutex( hHandle ); // Explicitly release mutex
   CloseHandle( hHandle ); // close handle before terminating
   return( 1 );
}

您必须确保正确关闭 - 程序崩溃, t删除mutex可能会阻止程序再次运行,虽然在理论上操作系统将清理任何悬挂互斥体一旦进程结束。

You have to make sure that you close properly - a program crash that doesn't remove the mutex could possibly prevent the program from running again, though in theory the OS will clean up any dangling mutexes once the process ends.

另一种常用的方法是搜索窗口标题的程序标题:

Another method commonly used is to search window titles for the program title:

HWND hWnd=::FindWindow(LPCTSTR lpClassName, // pointer to class name
                       LPCTSTR lpWindowName // pointer to window name
                       );

如果它为空,则找不到窗口,因此程序未运行。您可以在关闭此新实例之前使用它来关注正在运行的应用程序,因此用户不会想知道应用程序为什么没有打开。

If it's null, then the window was not found, therefore the program is not running. You can use this to bring focus to the running app before closing this new instance, so the user isn't left wondering why the app didn't open.

if(hWnd != NULL)
{
   ShowWindow(hWnd,SW_NORMAL);
   // exit this instance
   return(1);
}