main.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "mainwindow.h"
  2. #include <QApplication>
  3. #include <QFileDialog>
  4. #include <QSettings>
  5. #include <windows.h>
  6. #include <QDebug>
  7. #include <Tlhelp32.h>
  8. #include <cstdlib>
  9. #include <QDateTime>
  10. #include <QTextStream>
  11. #include <stdlib.h>
  12. #include <QProcess>
  13. #include <string.h>
  14. using namespace std;
  15. #define KEY_EXE_PATH "ALARM_PATH"
  16. BOOL IsExistProcess(const char* szProcessName)
  17. {
  18. PROCESSENTRY32 processEntry32;
  19. HANDLE toolHelp32Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  20. if (((int)toolHelp32Snapshot) != -1)
  21. {
  22. processEntry32.dwSize = sizeof(processEntry32);
  23. if (Process32First(toolHelp32Snapshot, &processEntry32))
  24. {
  25. do
  26. {
  27. size_t i;
  28. int iLen = 2 * wcslen(processEntry32.szExeFile);
  29. char* chRtn = new char[iLen + 1];
  30. //转换成功返回为非负值
  31. wcstombs_s(&i,chRtn,iLen + 1, processEntry32.szExeFile, iLen + 1);
  32. if (strcmp(szProcessName, chRtn) == 0)
  33. {
  34. return TRUE;
  35. }
  36. } while (Process32Next(toolHelp32Snapshot, &processEntry32));
  37. }
  38. CloseHandle(toolHelp32Snapshot);
  39. }
  40. //
  41. return FALSE;
  42. }
  43. int main(int argc, char *argv[])
  44. {
  45. QApplication a(argc, argv);
  46. MainWindow w;
  47. w.show();
  48. QSettings sets("sys.ini", QSettings::IniFormat);
  49. QString exeAbsPath = sets.value(KEY_EXE_PATH).toString();
  50. if ("" == exeAbsPath) {
  51. QString exepath = QFileDialog::getOpenFileName(0, "选择程序", "D:/zyj/QT/build-ProcessTest-Desktop_Qt_5_12_8_MSVC2017_32bit-Debug/debug", "Exe files (ProcessTest.exe)");
  52. qDebug() << exepath;
  53. if ("" != exepath) {
  54. sets.setValue(KEY_EXE_PATH, exepath);
  55. }
  56. } else {
  57. // 检测程序是否还在运行
  58. while (1) {
  59. QString loginfo;
  60. QFile file("restart_alarm_recored.txt");
  61. exeAbsPath = sets.value(KEY_EXE_PATH).toString();
  62. QString exeName = exeAbsPath.split('/').last();
  63. if(!IsExistProcess(exeName.toStdString().c_str())){
  64. loginfo += QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
  65. loginfo += "|";
  66. loginfo += exeName;
  67. loginfo += "|";
  68. loginfo += "restart\n";
  69. file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append);
  70. QTextStream out(&file);
  71. out << loginfo;
  72. file.close();
  73. //开启进程
  74. //system("start /b uugw04040003.exe");
  75. system(exeAbsPath.toStdString().c_str());
  76. }else{
  77. }
  78. }
  79. // 关闭状态重启
  80. }
  81. return a.exec();
  82. }