VC/MFC应用禁止多开

	// VC/MFC应用禁止多开
	// 编译环境:VS2017
	// MFC在 InitInstance 中创建Mutex来防止多开
	HANDLE hMutex;
	//hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, theApp.m_pszAppName);
	// 创建互斥体
	hMutex = CreateMutex(NULL, FALSE, _T("Microsoft"));
	DWORD dwError = GetLastError();
	if (NULL == hMutex)
	{
		CString szMsg;
		szMsg.Format(_T("CreateMutex error:%d\n"), dwError);
		OutputDebugString(szMsg);
	}
	else
	{
		if (ERROR_ALREADY_EXISTS == dwError)
		{	//互斥体已存在,发送WM_QUIT消息退出
			OutputDebugString(_T("CreateMutex opened an existing mutex.\n"));
			CloseHandle(hMutex);
			//PostQuitMessage(0);
			//PostMessage(theApp.m_pMainWnd->m_hWnd, WM_QUIT, 0, 0);
			//PostMessage(AfxGetMainWnd()->GetSafeHwnd(), WM_QUIT, 0, 0);
			PostMessage(NULL, WM_QUIT, (WPARAM)1, 0);
		}
		else
		{
			// 正常流程
			OutputDebugString(_T("CreateMutex created a new mutex.\n"));

			CMutexDlg dlg;
			m_pMainWnd = &dlg;
			INT_PTR nResponse = dlg.DoModal();
			if (nResponse == IDOK)
			{
				//  “确定”来关闭对话框的代码
			}
			else if (nResponse == IDCANCEL)
			{
				//  “取消”来关闭对话框的代码
			}
			else if (nResponse == -1)
			{
				TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n");
			}
			CloseHandle(hMutex);
		}
	}

猜你喜欢

转载自blog.csdn.net/k83133058/article/details/112922476
今日推荐