Win-API -02 获取窗口句柄
- 简 介
- 下 载
- 留 言
- 说 明
在Windows中,句柄是一个系统内部数据结构的引用。例如当你操作一个窗口,或说是一个Delphi窗体时,系统会给你一个该窗口的句柄,系统会通知你:你正在操作142号窗口,就此你的应用程序就能要求系统对142号窗口进行操作——移动窗口、改变窗口大小、把窗口最小化等等。实际上许多Windows API函数把句柄作为它的第一个参数,如GDI(图形设备接口)句柄、菜单句柄、实例句柄、位图句柄等,不仅仅局限于窗口函数。换句话说,句柄是一种内部代码,通过它能引用受系统控制的特殊元素,如窗口、位图、图标、内存块、光标、字体、菜单等
FindWindow函数获取窗口句柄
因为FindWindowA(LPCSTR lpClassName ,LPCSTR lpWindowName);既可以通过窗口类名又可以通过窗口名称查找窗口句柄,如果只知道一个就把另一个写成null.通常窗口名称会随着软件内容变化而变化,所以通过窗口名来查找窗口句柄是不明智的,因此我们用窗口类名获得窗口句柄。
#include <Windows.h> #include <stdio.h> #include <string.h> #include <iostream.h> int main(int argc, char* argv[]) { //根据窗口类名获取酷我音乐窗口句柄 HWND hq=FindWindow("kwmusicmaindlg",NULL); //得到酷我音乐窗口大小 RECT rect; GetWindowRect(hq,&rect); int w=rect.right-rect.left,h=rect.bottom-rect.top; cout<<"宽:"<<w<<" "<<"高:"<<h<<endl; //移动酷我音乐窗口位置 MoveWindow(hq,100,100,w,h,false); //得到桌面窗口 HWND hd=GetDesktopWindow(); GetWindowRect(hd,&rect); w=rect.right-rect.left; h=rect.bottom-rect.top; cout<<"宽:"<<w<<" "<<"高:"<<h<<endl; return 0; }
获取所有顶层窗口以及它们的子窗口
#include <Windows.h> #include <stdio.h> #include <tchar.h> #include <string.h> #include <iostream.h> int Pnum=0,Cnum;//父窗口数量,每一级父窗口的子窗口数量 //--------------------------------------------------------- //EnumChildWindows回调函数,hwnd为指定的父窗口 //--------------------------------------------------------- BOOL CALLBACK EnumChildWindowsProc(HWND hWnd,LPARAM lParam) { char WindowTitle[100]={0}; Cnum++; ::GetWindowText(hWnd,WindowTitle,100); printf("--|%d :%s\n",Cnum,WindowTitle); return true; } //--------------------------------------------------------- //EnumWindows回调函数,hwnd为发现的顶层窗口 //--------------------------------------------------------- BOOL CALLBACK EnumWindowsProc(HWND hWnd,LPARAM lParam) { if(GetParent(hWnd)==NULL && IsWindowVisible(hWnd)) //判断是否顶层窗口并且可见 { Pnum++; Cnum=0; char WindowTitle[100]={0}; ::GetWindowText(hWnd,WindowTitle,100); printf("-------------------------------------------\n"); printf("%d: %s\n",Pnum,WindowTitle); EnumChildWindows(hWnd,EnumChildWindowsProc,NULL); //获取父窗口的所有子窗口 } return true; } //--------------------------------------------------------- //main函数 //--------------------------------------------------------- int main() { //获取屏幕上所有的顶层窗口,每发现一个窗口就调用回调函数一次 EnumWindows(EnumWindowsProc ,NULL ); getchar(); return 0; }
GetDesktopWindow和GetNextWindow函数得到所有的子窗口
#include <Windows.h> #include <stdio.h> #include <tchar.h> #include <string.h> #include <iostream.h> int main() { HWND hd=GetDesktopWindow(); //得到桌面窗口 hd=GetWindow(hd,GW_CHILD); //得到屏幕上第一个子窗口 char s[200]={0}; int num=1; while(hd!=NULL) //循环得到所有的子窗口 { memset(s,0,200); GetWindowText(hd,s,200); cout<<num++<<": "<<s<<endl; hd=GetNextWindow(hd,GW_HWNDNEXT); } getchar(); return 0; }