本文介绍了如何在 C++ 中按名称获取进程句柄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我正在尝试获取例如 example.exe 的进程句柄,以便我可以在其上调用 TerminateProcess
.我怎样才能做到这一点?请注意,它没有窗口,所以 FindWindow
将不起作用.
I'm trying to get the process handle of, say example.exe, so I can call TerminateProcess
on it. How can I do this? Notice, it doesn't have a window so FindWindow
won't work.
推荐答案
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
int main( int, char *[] )
{
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (stricmp(entry.szExeFile, "target.exe") == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
// Do stuff..
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return 0;
}
另外,如果你想在 OpenProcess 中使用 PROCESS_ALL_ACCESS,你可以试试这个:
Also, if you'd like to use PROCESS_ALL_ACCESS in OpenProcess, you could try this:
#include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
void EnableDebugPriv()
{
HANDLE hToken;
LUID luid;
TOKEN_PRIVILEGES tkp;
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = luid;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);
CloseHandle(hToken);
}
int main( int, char *[] )
{
EnableDebugPriv();
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry) == TRUE)
{
while (Process32Next(snapshot, &entry) == TRUE)
{
if (stricmp(entry.szExeFile, "target.exe") == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
// Do stuff..
CloseHandle(hProcess);
}
}
}
CloseHandle(snapshot);
return 0;
}
这篇关于如何在 C++ 中按名称获取进程句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!