要确定一个.exe文件是否在C++中运行,可以使用以下方法:
CreateProcess
函数:CreateProcess
函数可以创建一个新的进程,并运行指定的可执行文件。在创建进程时,可以通过设置CREATE_SUSPENDED
标志来暂停进程的执行,从而确定.exe文件是否在C++中运行。
示例代码:
#include<Windows.h>
#include<iostream>
int main() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// 创建进程
if (!CreateProcess("path_to_exe_file", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
std::cout << "CreateProcess failed."<< std::endl;
return 0;
}
// 确认进程是否在运行
DWORD exitCode;
GetExitCodeProcess(pi.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
std::cout << ".exe文件正在运行。"<< std::endl;
} else {
std::cout << ".exe文件未运行。"<< std::endl;
}
// 恢复进程执行
ResumeThread(pi.hThread);
// 关闭进程和线程句柄
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 0;
}
ShellExecuteEx
函数:ShellExecuteEx
函数可以运行指定的可执行文件,并返回一个SHELLEXECUTEINFO
结构体,其中包含有关执行操作的信息。可以通过检查hProcess
成员来确定.exe文件是否在C++中运行。
示例代码:
#include<Windows.h>
#include<iostream>
#include <Shellapi.h>
int main() {
SHELLEXECUTEINFO sei;
ZeroMemory(&sei, sizeof(sei));
sei.cbSize = sizeof(sei);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpFile = "path_to_exe_file";
sei.nShow = SW_SHOW;
// 运行.exe文件
if (!ShellExecuteEx(&sei)) {
std::cout << "ShellExecuteEx failed."<< std::endl;
return 0;
}
// 确认进程是否在运行
DWORD exitCode;
GetExitCodeProcess(sei.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
std::cout << ".exe文件正在运行。"<< std::endl;
} else {
std::cout << ".exe文件未运行。"<< std::endl;
}
// 关闭进程句柄
CloseHandle(sei.hProcess);
return 0;
}
这两种方法都可以用于确定.exe文件是否在C++中运行。使用CreateProcess
函数可以在进程创建时暂停进程执行,从而确定进程是否在运行。而使用ShellExecuteEx
函数则可以直接运行.exe文件,并通过检查hProcess
成员来确定进程是否在运行。
领取专属 10元无门槛券
手把手带您无忧上云