检测是否打开多个同一软件
//多开检测
bool MultRunChecker(TSTRING strKey);
//多开检测
if (!MultRunChecker((_T("XXXXXX"))))
{
return 1;
}
bool MultRunChecker(TSTRING strKey)
{
HANDLE hMutex = CreateMutex(NULL, FALSE, strKey.c_str());
if (GetLastError() == ERROR_ALREADY_EXISTS)
{//已有实例在运行
//将已经运行的实例置顶
HWND hWnd = ::FindWindow(NULL, strKey.c_str());
::SetWindowPos(hWnd, HWND_TOP, -1, -1, -1, -1, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE | SWP_NOOWNERZORDER);
::ShowWindow(hWnd, SW_SHOWMINIMIZED);
::SetForegroundWindow(hWnd);
::ShowWindow(hWnd, SW_SHOWNORMAL);
Sleep(10);
if (::GetForegroundWindow() != hWnd)
{//如果置顶失败,则可能是残留进程,强制终止原有进程
TSTRING strExe = strKey + _T(".exe");
DWORD Pid = GetProcessidFromName(strExe.c_str());
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, Pid);
if (hProcess)
{
if (TerminateProcess(hProcess, 0))
{
return true;
}
}
}
return false;
}
return true;
}
//获取线程ID
DWORD GetProcessidFromName(LPCTSTR name)
{
PROCESSENTRY32 pe;
DWORD id = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(hSnapshot, &pe))
return 0;
while (1)
{
pe.dwSize = sizeof(PROCESSENTRY32);
if (Process32Next(hSnapshot, &pe) == FALSE)
break;
if (StrCmpW(pe.szExeFile, name) == 0)
{
id = pe.th32ProcessID;
break;
}
}
CloseHandle(hSnapshot);
return id;
}