TerminateProcess not working in Windows 7
I am writing an application in c++ on win7 platf开发者_运维知识库orm which needs to close another application. The steps I use are:
- Enumerate all processes with EnumProcess().
- Open a Process handle with OpenProcess(). The access rights are PROCESS_ALL_ACCESS|PROCESS_VM_READ.
- Then enumerate process modules with EnumProcessModules()
- I extract the module name with GetModuleBaseName() and compare it with the process name that I have.
- When I find a match, I use TerminateProcess() to kill the process.
The problem I am facing is this works in WindowsXP but not in Windows 7(64 bit). Using getlasterror(), I get the error as "Access Denied". I guess it has something to do with access rights. Is there any way I can do this on both the platforms? Or is there an API specific to win7?
I had the same problem. Been looking very long for an answer and finally found it.
When you want to terminate another program you need a handle. A handle needs permissions to work with the other process. Terminating the process needs a specific permissions called PROCESS_TERMINATE
. Use that when opening a handle for termination and it will probably work. It did for me, on Windows 7.
To sum things up, here the code you need to correctly use TerminateProcess
. Handle with care ;)
Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessID As Long) As Long
Declare Function TerminateProcess Lib "kernel32.dll" ( _
ByVal ApphProcess As Long, _
ByVal uExitCode As Long) As Long
Const PROCESS_TERMINATE = &H1
Private Sub KillProcess(ByVal ProcessID As Long)
Dim pHandle As Long
pHandle = OpenProcess(PROCESS_TERMINATE, 0, ProcessID)
Call TerminateProcess(pHandle, 0)
End Sub
Are you running your program with Administrator privileges, and are you terminating processed of the same user?
精彩评论