如何枚举 Windows 顶级桌面窗口?

bool is_top_level_window(HWND hwnd) {
	if (!IsWindow(hwnd)) return false;

	DWORD dw_style = GetWindowLongPtr(hwnd, GWL_STYLE);
	DWORD dw_exstyle = GetWindowLongPtr(hwnd, GWL_EXSTYLE);

	DWORD includes = WS_CHILDWINDOW;
	DWORD excludes = WS_VISIBLE /*| WS_MINIMIZEBOX*/;

	if ((dw_style & includes) != 0 || (dw_style & excludes) != excludes)
		return false;

	includes = WS_EX_TOOLWINDOW | WS_EX_NOREDIRECTIONBITMAP;
	excludes = 0;

	if ((dw_exstyle & includes) != 0 || (dw_exstyle & excludes) != excludes)
		return false;

	if (dw_style & WS_POPUP) {
		if (GetParent(hwnd) != NULL) {
			excludes = WS_EX_OVERLAPPEDWINDOW;
			if ((dw_exstyle & excludes) != excludes) {
				return false;
			}
		}
	}
	return true;
}

BOOL CALLBACK EnumWindowProc(HWND hwnd, LPARAM lParam) {
	if (is_top_level_window(hwnd)) {
		char buff[1024] = { 0 };
		buff[GetWindowTextA(hwnd, buff, _countof(buff))] = '';
		DWORD processId = 0;
		GetWindowThreadProcessId(hwnd, &processId);
		printf("%08X - %08X - %s
", processId, hwnd, buff);
	}
	return TRUE;
}

int enum_windows() {
	// 获取当前桌面句柄,无需释放
	HDESK hDesk = GetThreadDesktop(GetCurrentThreadId());
	printf("PID	   HWND       Title
");
	return EnumDesktopWindows(hDesk, EnumWindowProc, 0) ? 0 : -1;
}


int main()
{
	enum_windows();
	getchar();
	return 0;
}
原文地址:https://www.cnblogs.com/cheungxiongwei/p/9364502.html