使用ShellExecuteEx启动Kill进程

时间:2012-11-02 10:47:25

标签: c++ winapi process pid

1)我使用ShellExecuteEx

启动了一个进程

2)用

检索PID
GetProcessId(shellExInfo.hProcess)

示例代码:

SHELLEXECUTEINFO shellExInfo;

shellExInfo.cbSize = sizeof(SHELLEXECUTEINFO);
shellExInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shellExInfo.hwnd = NULL;
shellExInfo.lpVerb = "open";
shellExInfo.lpFile = processToStart.c_str();
shellExInfo.lpParameters = processParams.c_str();
shellExInfo.lpDirectory = NULL;
shellExInfo.nShow = SW_SHOW;
shellExInfo.hInstApp = NULL;

ShellExecuteEx(&shellExInfo); // start process

GetProcessId(shellExInfo.hProcess); // retrieve PID

现在我想用给定的PID杀死已启动的进程!这怎么可能?

THX

1 个答案:

答案 0 :(得分:3)

要终止进程,您必须使用TerminateProcess函数。但是,它接收进程的句柄作为参数:

TerminateProcess(shellExInfo.hProcess, 1);

如果由于某种原因您只存储了进程ID而不是句柄,那么您应该首先使用OpenProcess函数打开句柄:

HANDLE h = OpenProcess(PROCESS_TERMINATE, false, process_id);
TerminateProcess(h, 1);
CloseHandle(h);