启动另一个进程STARTUPINFO startupInfo; CString strStartPath1 = GetMainExeDir() + _T("xxxx\\xxxx.exe"); ZeroMemory( &startupInfo, sizeof( startupInfo ) ); startupInfo.cb = sizeof( startupInfo ); startupInfo.dwFlags = STARTF_USESHOWWINDOW; // 使特定成员有效 startupInfo.wShowWindow = (WORD)SW_SHOW; PROCESS_INFORMATION processInfo; DWORD dwErr = 0; if (!CreateProcess(strStartPath1, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo/*processInfo*/)) { dwErr = GetLastError(); }
关闭另一个进程sItemText为进程名称
PROCESSENTRY32 pe; HANDLE hProcess; CString filepath; HANDLE hShot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); pe.dwSize=sizeof(PROCESSENTRY32); if(Process32First(hShot,&pe)) { do { if(wcscmp(pe.szExeFile,sItemText)==0) { hProcess=OpenProcess(PROCESS_ALL_ACCESS,FALSE,pe.th32ProcessID); TerminateProcess(hProcess,0); } } while(Process32Next(hShot,&pe)); } CloseHandle(hShot); return 0;
获取主exe路径
CString path; GetModuleFileName(NULL,path.GetBufferSetLength(MAX_PATH+1),MAX_PATH); path.ReleaseBuffer(); int pos = path.ReverseFind('\\'); path = path.Left(pos);
使同時只有一個進程在運行
CString name = _T("yourProcess.exe"); //進程名稱 CreateMutex(NULL, TRUE, MutexGUID); if (GetLastError() == ERROR_ALREADY_EXISTS) { //HWND hRet = FindWindow(NULL, _T("BEProjectUpload.exe")); PROCESSENTRY32 pe; DWORD processID = 0; //snap快照 HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe.dwSize = sizeof(PROCESSENTRY32); //减速上一步获得的windows的快照的每个进程,first,next函数 if (!Process32First(hSnapshot, &pe)) { return 0; } CString name1, name2; do { pe.dwSize = sizeof(PROCESSENTRY32); name1 = pe.szExeFile; name2 = name; name1.MakeUpper(); name2.MakeUpper(); //FindWindow() if (name1 == name2) { processID = pe.th32ProcessID; break; } if (Process32Next(hSnapshot, &pe) == FALSE) { break; } } while (1); CloseHandle(hSnapshot); return FALSE; }