VC++ 通过进程名或进程ID获取进程句柄
HANDLE GetProcessHandle(int nID)//通过进程ID获取进程句柄
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}
HANDLE GetProcessHandle(LPCTSTR pName)//通过进程名获取进程句柄
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe)) {
if (!_tcscmp(pe.szExeFile, pName)) {
CloseHandle(hSnapshot);
return GetProcessHandle(pe.th32ProcessID);
}
}
return NULL;
}
VC由进程ID获取窗口句柄
HWND GetWindowHandleByPID(DWORD dwProcessID)
{
HWND h = GetTopWindow(0);
while ( h )
{
DWORD pid = 0;
DWORD dwTheardId = GetWindowThreadProcessId( h,&pid);
if (dwTheardId != 0)
{
if ( pid == dwProcessID/*your process id*/ )
{
// here h is the handle to the window
return h;
}
}
h = GetNextWindow( h , GW_HWNDNEXT);
}
return NULL;
}
HWND GetHwndByPid(DWORD ProcessId)//进程ID取窗口句柄
{
WINDOWINFO WinInfo1[255];
HWND _hwnd=0;
DWORD aa=EnumWindowInfo(WinInfo1);
for(int i=0;i<aa;i++)
{
if (WinInfo1[i].dwProcessId==ProcessId)
{
_hwnd=WinInfo1[i].hwnd1;
if (0 ==::GetWindowLong(WinInfo1[i].hwnd1,GWL_HWNDPARENT))
{
return WinInfo1[i].hwnd1;
}
}
}
return _hwnd;
}
回调函数找
typedef struct tagWNDINFO
{
DWORD dwProcessId;
HWND hWnd;
} WNDINFO, *LPWNDINFO;
BOOL CALLBACK YourEnumProc(HWND hWnd,LPARAM lParam)
{
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
LPWNDINFO pInfo = (LPWNDINFO)lParam;
if(dwProcessId == pInfo->dwProcessId)
{
pInfo->hWnd = hWnd;
return FALSE;
}
return TRUE;
}
HWND GetProcessMainWnd(DWORD dwProcessId)
{
WNDINFO wi;
wi.dwProcessId = dwProcessId;
wi.hWnd = NULL;
EnumWindows(YourEnumProc,(LPARAM)&wi);
return wi.hWnd;
}