强制终止指定路径的进程(QString 版本)
| 131 | |
| 132 | // 强制终止指定路径的进程(QString 版本) |
| 133 | void Utils::killProcessByPath(const QString& targetPath) { |
| 134 | // 检查文件是否存在(严格模式) |
| 135 | if (!QFileInfo::exists(targetPath)) { |
| 136 | qDebug() << "目标文件不存在:" << targetPath; |
| 137 | return; |
| 138 | } |
| 139 | |
| 140 | // 转换为Windows原生路径格式(保留原始大小写和格式) |
| 141 | const std::wstring target = QDir::toNativeSeparators(targetPath).toStdWString(); |
| 142 | |
| 143 | // 创建进程快照 |
| 144 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); |
| 145 | if (hSnapshot == INVALID_HANDLE_VALUE) { |
| 146 | qWarning() << "创建进程快照失败,错误码:" << GetLastError(); |
| 147 | return; |
| 148 | } |
| 149 | |
| 150 | PROCESSENTRY32W pe = { sizeof(PROCESSENTRY32W) }; |
| 151 | bool processFound = false; |
| 152 | |
| 153 | if (Process32FirstW(hSnapshot, &pe)) { |
| 154 | do { |
| 155 | HANDLE hProcess = OpenProcess( |
| 156 | PROCESS_QUERY_INFORMATION | PROCESS_TERMINATE, |
| 157 | FALSE, |
| 158 | pe.th32ProcessID |
| 159 | ); |
| 160 | |
| 161 | if (hProcess) { |
| 162 | wchar_t exePath[MAX_PATH] = {0}; |
| 163 | DWORD bufSize = MAX_PATH; |
| 164 | |
| 165 | // 使用兼容性更好的函数获取路径 |
| 166 | if (GetModuleFileNameExW(hProcess, NULL, exePath, bufSize)) { |
| 167 | // 标准化路径格式 |
| 168 | std::wstring processPath = exePath; |
| 169 | processPath = QDir::toNativeSeparators( |
| 170 | QString::fromWCharArray(processPath.c_str()) |
| 171 | ).toStdWString(); |
| 172 | |
| 173 | // 不区分大小写比较 |
| 174 | if (_wcsicmp(processPath.c_str(), target.c_str()) == 0) { |
| 175 | if (TerminateProcess(hProcess, 1)) { |
| 176 | qInfo() << "已终止进程:" << targetPath; |
| 177 | processFound = true; |
| 178 | } else { |
| 179 | qWarning() << "终止进程失败,PID:" |
| 180 | << pe.th32ProcessID << "错误码:" << GetLastError(); |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | CloseHandle(hProcess); |
| 185 | } |
| 186 | } while (Process32NextW(hSnapshot, &pe)); |
| 187 | } |
| 188 | |
| 189 | CloseHandle(hSnapshot); |
| 190 |
nothing calls this directly
no outgoing calls
no test coverage detected