#include <Windows.h>
#include <iostream>
#include <string>
static BOOL CALLBACK enumchildWindowCallback(HWND hWnd, LPARAM lparam) {
int length = GetWindowTextLength(hWnd);
char * buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
std::cout << hWnd << ": " << windowTitle << std::endl;
delete buffer;
return TRUE;
}
int main()
{
HWND hwnd = (HWND)0x000D0DEE; //父窗口的句柄
EnumChildWindows(hwnd, enumchildWindowCallback, NULL);
std::cin.ignore();
return 0;
}
拓展: 使用EnumWindows枚举窗口句柄(不包括子窗口)
#include <Windows.h>
#include <string>
#include <iostream>
static BOOL CALLBACK enumchildWindowCallback(HWND hWnd, LPARAM lparam) {
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
int n = (int)hWnd;
// Ignore windows if invisible or missing a title
// if (IsWindowVisible(hWnd) && length != 0) {
std::cout << n << ": " << windowTitle << std::endl;
// }
delete buffer;
return TRUE;
}
static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM m) {
TCHAR _classbuf[255];
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
m = GetClassName(hWnd, _classbuf, 1024);
int n = (int)hWnd;
// Ignore windows if invisible or missing a title
// if (IsWindowVisible(hWnd) && length != 0) {
std::cout << n << ": " << windowTitle << std::endl;
// EnumChildWindows(hWnd, enumchildWindowCallback, m);
// }
return TRUE;
}
int main()
{
std::cout << "Enmumerating windows..." << std::endl;
EnumWindows(enumWindowCallback, NULL);
std::cin.ignore();
return 0;
}
如果去掉EnumChildWindows(hWnd, enumWindowCallback, m)的注释,将会枚举所有的窗口
更新之后的版本:
#include <Windows.h>
#include <iostream>
#include <tchar.h>
static BOOL CALLBACK enumchildWindowCallback(HWND hWnd, LPARAM lparam) {
TCHAR buffer[256] = {};
GetWindowText(hWnd, buffer, 256);
int n = (int)hWnd;
if (IsWindowVisible(hWnd))
{
RECT rc;
GetWindowRect(hWnd, &rc);
_tprintf(TEXT("0x%x : %s %d %d\n"), n, buffer, rc.right - rc.left, rc.bottom - rc.top);
}
return TRUE;
}
static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM m) {
TCHAR buffer[256] = {};
GetWindowText(hWnd, buffer, 256);
int n = (int)hWnd;
if (IsWindowVisible(hWnd))
{
RECT rc;
GetWindowRect(hWnd, &rc);
_tprintf(TEXT("0x%x : %s %d %d\n"), n, buffer, rc.right - rc.left, rc.bottom - rc.top);
EnumChildWindows(hWnd, enumchildWindowCallback, m);
}
return TRUE;
}
int main()
{
_tprintf(TEXT("Enmumerating windows..."));
EnumWindows(enumWindowCallback, NULL);
return 0;
}