仅启动MFC基于对话框的应用程序的一个实例

1 mfc visual-c++

我创建了一个基于MFC对话框的应用程序.

我启动了应用程序,它工作正常.现在,在它运行时,我再次启动应用程序,然后启动它的另一个实例.

但是,我不想要他的行为; 如果应用程序已在运行,我想防止创建它的新实例.

请给我代码.

Chr*_*sBD 9

在调用应用程序对话框类之前,请尝试在main中调用以下函数.如果它返回False,那么不要创建对话框而是退出.

BOOL init()
{
   HANDLE mutex = CreateMutex(NULL, FALSE, "mutexname");
   if(mutex == NULL)
   {
      return FALSE;
   }

   if (GetLastError() == ERROR_ALREADY_EXISTS)
   { 
       /* You only need the message box if you wish to notify the user 
          that the process is running*/
       MessageBox("Another instance is already running.");
       return FALSE;
   }

   return TRUE;
} 
Run Code Online (Sandbox Code Playgroud)

确保互斥锁名称是唯一的,使用VS生成GUID并以字符串形式将其用作互斥锁名称.