1. 顶级窗口查找与修改
1.0 FindWindow函数解析
1.函数定义如下:
HWND FindWindowA( LPCSTR lpClassName, //类名,注册窗口时候调用RegisterClass设置的名称,如果填NULL表示忽略类名 LPCSTR lpWindowName //窗口标题名称 );
1.1 修改主窗口标题示例
1.打开一个记事本程序,默认标题如下图所示为无标题 - 记事本
:
2.获取这个记事本的句柄,代码如下:
#include "stdafx.h" #include <windows.h> int main(int argc, char* argv[]) { HWND hwnd = ::FindWindow(NULL,"无标题 - 记事本"); if(hwnd != NULL) { //修改窗口标题 ::SetWindowText(hwnd,"记事本标题修改测试"); } else { ::MessageBox(NULL,TEXT("窗口没有找到"),TEXT("[ERROR]"),MB_OK); } }
3.运行后效果如下图:
1.2 控制主窗口
获取记事本窗口句柄,切换到记事本窗口,三秒后关闭,代码如下:
#include "stdafx.h" #include <windows.h> int main(int argc, char* argv[]) { HWND hwnd = ::FindWindow(NULL,TEXT("无标题 - 记事本")); if(hwnd != NULL) { typedef void (WINAPI *PSWITCHTOTHISWINDOW) (HWND,BOOL); PSWITCHTOTHISWINDOW SwitchToThisWindow; HMODULE hUser32=LoadLibrary("user32.dll"); SwitchToThisWindow=(PSWITCHTOTHISWINDOW)GetProcAddress(hUser32,"SwitchToThisWindow"); //切换窗口 SwitchToThisWindow(hwnd,false); Sleep(3000);//等待三秒 //关闭窗口 ::SendMessage(hwnd,WM_CLOSE,0,0); } else { ::MessageBox(NULL,TEXT("窗口没有找到"),TEXT("[ERROR]"),MB_OK); } }
2.子窗口的查找与修改
2.1 子窗口的查找
void Test() { HWND hParentwnd = NULL; hParentwnd = FindWindow(NULL, TEXT("ParentWnd")); while(true) { HWND hwnd = NULL; HWND hwndTmp = ::FindWindowEx(hParentwnd, hwnd, NULL, TEXT("ChildWnd")); if(!hwndTmp) { ::MessageBox(NULL,TEXT("窗口没有找到"),TEXT("[ERROR]"),MB_OK); break; } else { ::SetWindowText(hwndTmp,"文本框新的标题"); //::SendMessage(hwndTmp,WM_SETTEXT,0,(LPARAM)"新的内容"); } } }
2.2.枚举子窗口
#include "stdafx.h" #include <windows.h> BOOL CALLBACK EnumChildProc(HWND hWnd,LPARAM lParam) { TCHAR szTitle[MAX_PATH] = {0}; ::GetWindowText(hWnd,szTitle,MAX_PATH); MessageBox(NULL,szTitle,"[子窗口]",MB_OK); return true; } int main(int argc, char* argv[]) { HWND hWnd = ::FindWindow(NULL,TEXT("无标题 - 记事本")); if(hWnd != NULL) { ::EnumChildWindows(hWnd,EnumChildProc,0); } else { ::MessageBox(NULL,TEXT("窗口没有找到"),TEXT("[ERROR]"),MB_OK); } }
3.模拟鼠标点击
#include "stdafx.h" #include <windows.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )//隐藏控制台 int main(int argc, char* argv[]) { TCHAR szTitle[MAX_PATH] = {0}; RECT r; HWND hwnd = ::FindWindow(TEXT("#32770"),TEXT("飞鸽传书 IP Messenger")); if(hwnd != NULL) { HWND hButton = FindWindowEx(hwnd,NULL,"Button","刷新(&R)"); //获取窗口坐标 ::GetWindowRect(hButton,&r); printf("%d %d",r.left,r.top); //设置鼠标的位置 ::SetCursorPos(r.left+10,r.top+10); Sleep(2000); //鼠标左键单击 mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);//点下左键 mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);//松开左键 } else { ::MessageBox(NULL,TEXT("窗口没有找到"),TEXT("[ERROR]"),MB_OK); } }