有几个方式来枚举窗口,下面的几个函数可能需要配合使用才能找到你想要的窗口:
1 EnumWindow:枚举所有顶级窗口。可以枚举到一个程序的顶级窗口,但有可能枚举不到程序弹出来的模式对话框。
2 EnumChildWindow: 枚举一个窗口的子窗口。可以枚举某个对话框里面的所有控件。
3 EnumThreadWindows: 枚举属于某个线程的所有窗口,可以枚举到模式对话框,但可能枚举不到对话框里面的控件。
3 FindWindow: 如果知道窗口的标题名,可以使用这个函数来得到窗口的名字。
4 WindowFromPoint: 得到占据了屏幕某一点的窗口的句柄。
#include <iostream>
#include <Windows.h>
#include <string.h>
using namespace std;
STARTUPINFO si;
PROCESS_INFORMATION pi;
BOOL CALLBACK EnumChildProc( HWND hWnd,
LPARAM lParam
)
{
//
TCHAR haha[256];
HWND hdlg;
GetWindowText(hWnd,haha,256);
wprintf(L"child %s\n",haha);
return true;
}
BOOL CALLBACK EnumThreadWndProc( HWND hWnd,
LPARAM lParam
)
{
//
TCHAR haha[256];
HWND hdlg;
GetWindowText(hWnd,haha,256);
wprintf(L"window %s\n",haha);
if(wcscmp(haha,L"Welcome to J-Flash")==0)
{
EnumChildWindows(hWnd,EnumChildProc,lParam);
}
return true;
}
BOOL CALLBACK EnumWindowCallBack(HWND hWnd, LPARAM lParam)
{
TCHAR buf[128];
GetWindowText(hWnd, buf, 128 );
if(wcsstr(buf,L"SEGGER J-Flash")!=0)
{
cout<<"main handle: "<<hWnd<<endl;
//EnumChildWindows(hWnd,EnumChildProc,lParam);
DWORD dwProcessId;
DWORD dwtheadid = GetWindowThreadProcessId(hWnd,&dwProcessId);
EnumThreadWindows(dwtheadid,EnumThreadWndProc,0);
if(FindWindow(NULL,L"Welcome to J-Flash"))
{
cout<<"success find windows"<<endl;
}
return false;
//找到目标了,返回false表示不再继续枚举了
}
return true; //继续枚举
}
DWORD WINAPI ThreadFun(LPVOID pM)
{
//printf("子线程的线程ID号为:%d\n子线程输出Hello World\n", GetCurrentThreadId());
EnumWindows(EnumWindowCallBack,0);
return 0;
}
int main()
{
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if(CreateProcess(L"D:/JLinkARM_V486b/JFlashARM.exe",NULL,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi)==0)
cout<<"error to create a process"<<endl;
Sleep(3000);
HANDLE handle = CreateThread(NULL, 0, ThreadFun, NULL, 0, NULL);
WaitForSingleObject(handle, INFINITE);
Sleep(5000);
TerminateProcess(pi.hProcess,0);
return 0;
}