admin管理员组

文章数量:1417555

I'm making an app that allows me to "control" the lifespan of an executable.

I have an app with a TStringList that has the address of several executable files (.exe). I would like to be able to launch them whenever I want, I already do this with ShellExecute(), but I don't know how I could close them when they are running.

I'm making an app that allows me to "control" the lifespan of an executable.

I have an app with a TStringList that has the address of several executable files (.exe). I would like to be able to launch them whenever I want, I already do this with ShellExecute(), but I don't know how I could close them when they are running.

Share Improve this question edited Jan 31 at 16:24 Remy Lebeau 601k36 gold badges508 silver badges851 bronze badges asked Jan 31 at 9:11 Robe79Robe79 595 bronze badges 3
  • 3 Instead of ShellExecute it is better to use CreateProcess! The parameter ProcessInformation can be used afterwards to check or control (close) the created processs. – DelphiCoder Commented Jan 31 at 9:29
  • C:\Windows\System32\taskkill.exe /im aprogram.exe /f /t – Pieter B Commented Jan 31 at 10:15
  • 1 @PieterB That's not programming, and it doesn't "close" processes gracefully - for that the process handle is better, from which you can get window handles to send them something like WM_CLOSE. – AmigoJack Commented Jan 31 at 12:29
Add a comment  | 

1 Answer 1

Reset to default 4

ShellExecute() does not return anything that can be used to control the launched process.

If you use ShellExecuteEx() instead, you can specify the SEE_MASK_NOCLOSEPROCESS flag, and then grab the SHELLEXECUTEINFO.hProcess field after launch. You can then use GetProcessId() on that handle to get the process id.

But, it would be better to use CreateProcess() instead, and grab the returned PROCESS_INFORMATION.dwProcessId and PROCESS_INFORMATION.hProcess fields.

Given the process id, you can then use EnumWindows() and GetWindowThreadProcessId() to find all of the top-level windows that belong to the process, and then you can send a WM_CLOSE or WM_QUIT message to each window. You can then use WaitForSingleObject(), or GetExitCodeProcess() in a loop, to monitor the process handle until the process exits or a timeout elapses.

If the process does not exit in a reasonable amount of time, then given the process handle, you can use TerminateProcess() to brute-force it.

本文标签: delphiRun and close filesexeStack Overflow