if you know hWnd, The GetWindowThreadProcessId function retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window. if you know hInstance, use EnumWindows to get all top level window handle, call GetWindowThreadProcessId to get its process, compare with the known id.
一个进程可以包括n个线程,进程起来以后才能创建线程。所以先由hProcess。
hProcess 是程序运行后最先创建的那个默认的,假定自己没有新建
hThread 是该进程的主线程
从程序主窗口句柄得到其它几个比较容易,
DWORD GetWindowThreadProcessId(
HWND hWnd, // handle to window
LPDWORD lpdwProcessId // process identifier
);
能得到指定窗口的创建进程和线程。从指定进程要得到进程的主窗口要通过遍历窗口来得到,遍历窗口的函数是EnumWindows进程得线程可通过这些函数:
hKernel = GetModuleHandle("KERNEL32.DLL");
if (hKernel)
{
pCreateToolhelp32Snapshot =
(CREATESNAPSHOT)GetProcAddress(hKernel, "CreateToolhelp32Snapshot");
pThread32First = (THREADWALK)GetProcAddress(hKernel, "Thread32First");
pThread32Next = (THREADWALK)GetProcAddress(hKernel, "Thread32Next");
}
1.由 hInstance : 无法得到其他几个,且其他几个也无法得到 hInstance
2.由 hWnd :
用 DWORD GetWindowThreadProcessId(
HWND hWnd, // handle to window
LPDWORD lpdwProcessId // process identifier
);
可得到主线程 ID , 再用
HANDLE OpenProcess(
DWORD dwDesiredAccess, // access flag
BOOL bInheritHandle, // handle inheritance option
DWORD dwProcessId // process identifier
);
可得到hProcess,再由3.的方法得到 hThread
3.由 hProcess :
(1).用 BOOL EnumWindows(
WNDENUMPROC lpEnumFunc, // callback function
LPARAM lParam // application-defined value
);
枚举所有的顶级窗口,再由2.的方法得到相应的hProcess1, 判断它是否等于已知的
hProcess
(2).可用 HWND GetWindow(
HWND hWnd, // handle to original window
UINT uCmd // relationship
);
找到所有的窗口,相对比 EnumWindows 简单些,但满些。
进程得线程可通过这些函数:
hKernel = GetModuleHandle("KERNEL32.DLL");
if (hKernel)
{
pCreateToolhelp32Snapshot =
(CREATESNAPSHOT)GetProcAddress(hKernel, "CreateToolhelp32Snapshot");
pThread32First = (THREADWALK)GetProcAddress(hKernel, "Thread32First");
pThread32Next = (THREADWALK)GetProcAddress(hKernel, "Thread32Next");
}
若用 GetCurrentThread() ,则只对本程序有效。
4.由 hThread 无法得到其他几个,但用2.3.的方法可以得到它。