通过进程名获取窗口句柄

#include "stdafx.h"
#include"bytetostr1.h"
#include
#include
#include   
#include   
#include   
HWND GetWindowHandleByPID(DWORD dwProcessID)//通过进程ID获取顶层窗口句柄
{
	HWND h = ::GetTopWindow(0);
	while (h)
	{
		DWORD pid = 0;
		DWORD dwTheardId = GetWindowThreadProcessId(h, &pid);
		if (dwTheardId != 0)
		{
			if (pid == dwProcessID)
			{
				// here h is the handle to the window
				while (::GetParent(h) != NULL)
					h = ::GetParent(h);
				return h;
			}
		}
		h = ::GetNextWindow(h, GW_HWNDNEXT);
	}
	return NULL;
}
int main()
{
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(pe32);
	HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	BOOL find = Process32First(hp, &pe32);
	HWND chuangkoujubing=0;
	while (find)
	{
		if (lstrcmp(pe32.szExeFile, L"zhengtu.dat") == 0)
		{
			//printf("%d", pe32.th32ProcessID);
			break;
		}
		find = Process32Next(hp, &pe32);
	}
	DWORD jinchengid = pe32.th32ProcessID;
	printf("进程id %d", jinchengid);
	chuangkoujubing = GetWindowHandleByPID(jinchengid);
	printf("窗口句柄 %d", chuangkoujubing);
	HANDLE jinchengjubing1 = OpenProcess(PROCESS_ALL_ACCESS, FALSE, jinchengid);
	//printf("获取进程句柄成功\n");
	printf("进程句柄%x\n", (DWORD)jinchengjubing1);
}

 

你可能感兴趣的:(通过进程名获取窗口句柄)