qt WINDOWS环境结束进程

虽然方法能查到,这里总结一下,以后方便回顾一下

1、QProcess

  1. QProcess p;
  2. QString c = "taskkill /im DingTalk.exe /f";
  3. p.execute(c);
  4. p.close();

直接执行CMD中的命令,注意空格!!!

2、系统API

根据进程名称先找到进程PID,再根据PID杀死进程

  1. #include <Windows.h>
  2. #include <tlhelp32.h>
  3. #include <string.h>
  4. using namespace std;
  5. /*根据进程名称杀死进程
  6. *1、根据进程名称找到PID
  7. *2、根据PID杀死进程
  8. */
  9. int killTaskl(const QString& exe)
  10. {
  11. //1、根据进程名称找到PID
  12. HANDLE hProcessSnap;
  13. PROCESSENTRY32 pe32;
  14. hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  15. if (hProcessSnap == INVALID_HANDLE_VALUE)
  16. {
  17. return -1;
  18. }
  19. pe32.dwSize = sizeof(PROCESSENTRY32);
  20. if (!Process32First(hProcessSnap, &pe32))
  21. {
  22. CloseHandle(hProcessSnap);
  23. return -1;
  24. }
  25. BOOL bRet = FALSE;
  26. DWORD dwPid = -1;
  27. while (Process32Next(hProcessSnap, &pe32))
  28. {
  29. //将WCHAR转成const char*
  30. int iLn = WideCharToMultiByte (CP_UTF8, 0, const_cast<LPWSTR> (pe32.szExeFile), static_cast< int>( sizeof(pe32.szExeFile)), NULL, 0, NULL, NULL);
  31. std:: string result (iLn, 0);
  32. WideCharToMultiByte (CP_UTF8, 0, pe32.szExeFile, static_cast< int>( sizeof(pe32.szExeFile)), const_cast<LPSTR> (result.c_str()), iLn, NULL, NULL);
  33. if ( 0 == strcmp(exe.toStdString().c_str(), result.c_str ()))
  34. {
  35. dwPid = pe32.th32ProcessID;
  36. bRet = TRUE;
  37. qDebug()<< "zhaodao";
  38. break;
  39. }
  40. }
  41. CloseHandle(hProcessSnap);
  42. qDebug()<<dwPid;
  43. 2、根据PID杀死进程
  44. HANDLE hProcess= NULL;
  45. //打开目标进程
  46. hProcess=OpenProcess(PROCESS_TERMINATE,FALSE,dwPid);
  47. if (hProcess== NULL) {
  48. qDebug()<< "Open Process fAiled ,error:"<<GetLastError();
  49. return -1;
  50. }
  51. //结束目标进程
  52. DWORD ret=TerminateProcess(hProcess, 0);
  53. if(ret== 0) {
  54. qDebug()<< "kill task faild,error:"<<GetLastError();
  55. return -1;
  56. }
  57. return 0;

猜你喜欢

转载自blog.csdn.net/u013934107/article/details/81000695
今日推荐