VC++如何获取目标程序的句柄hProcess

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiyanglin/article/details/80960404

方法一:

任务管理器找到程序的PID,通过PID获取hProcess

HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID);



方法二:

使用spy++获取目标程序窗口对应的句柄

通过窗口句柄获取PID,再使用方法一的函数获取hProcess 


HWND wnd = (HWND)0x0003069C;

DWORD pid;

GetWindowThreadProcessId(wnd, &pid);


方法三:

知道目标程序窗口的名称wndName

通过FindWindow获取窗口句柄,在通过方法二的函数进行获取

HWND wnd = ::FindWindow(NULL, wndName);



方法四:

只知道exe名称,通过遍历应用程序的名称获取运行的进程对应的pid,然后用这个pid使用方法一获取hProcess 


通过exe名称获取pid的方法如下:

#include <tlhelp32.h>

bool getPid(DWORD &findPID,CString findExeName)

{//findExeName名称中包含.exe

bool hasfind = false;

 

PROCESSENTRY32 pe32;

pe32.dwSize = sizeof(pe32);

HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

if (hProcessSnap == INVALID_HANDLE_VALUE)

{

AfxMessageBox(_T("CreateToolhelp32Snapshot调用失败!"));

return hasfind;

}

BOOL bMore = ::Process32First(hProcessSnap, &pe32);

while (bMore)

{

CString exeName = pe32.szExeFile;

DWORD pid = pe32.th32ProcessID;

if (exeName == findExeName)

{

findPID = pid;

hasfind = true;

break;

}

bMore = ::Process32Next(hProcessSnap, &pe32);

}

::CloseHandle(hProcessSnap);

 

return hasfind;

}


猜你喜欢

转载自blog.csdn.net/jiyanglin/article/details/80960404