我假设,我问的实际上应该是默认的,但我遇到了一些我不明白的行为。
#include "stdafx.h" using namespace std; BOOL CALLBACK enumWindowsProc( __in HWND hWnd, __in LPARAM lParam ) { if( !::IsIconic( hWnd ) ) { return TRUE; } int length = ::GetWindowTextLength( hWnd ); if( 0 == length ) return TRUE; TCHAR* buffer; buffer = new TCHAR[ length + 1 ]; memset( buffer, 0, ( length + 1 ) * sizeof( TCHAR ) ); GetWindowText( hWnd, buffer, length + 1 ); tstring windowTitle = tstring( buffer ); delete[] buffer; wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl; return TRUE; } int _tmain( int argc, _TCHAR* argv[] ) { wcout << TEXT( "Enumerating Windows..." ) << endl; BOOL enumeratingWindowsSucceeded = ::EnumWindows( enumWindowsProc, NULL ); cin.get(); return 0; }
如果我调用该代码,它将列出所有最小化的窗口:
现在,我不再只对最小化的窗口感兴趣,现在我想要所有的窗口。 所以我删除了IsIconic
检查:
BOOL CALLBACK enumWindowsProc( __in HWND hWnd, __in LPARAM lParam ) { /* if( !::IsIconic( hWnd ) ) { return TRUE; } */ int length = ::GetWindowTextLength( hWnd ); if( 0 == length ) return TRUE; TCHAR* buffer; buffer = new TCHAR[ length + 1 ]; memset( buffer, 0, ( length + 1 ) * sizeof( TCHAR ) ); GetWindowText( hWnd, buffer, length + 1 ); tstring windowTitle = tstring( buffer ); delete[] buffer; wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl; return TRUE; }
现在我得到除了最小化窗口之外的所有窗口(这次没有列出先前列出的窗口句柄):
为了完整性,这是stdafx.h
:
#pragma once #include "targetver.h" #include <iostream> #include <map> #include <string> namespace std { #if defined _UNICODE || defined UNICODE typedef wstring tstring; #else typedef string tstring; #endif } #include <stdio.h> #include <tchar.h> #include <Windows.h> #include <psapi.h>
那么, wcout.flush()
永远不会工作,但wcout.clear()
修复你的代码,至少对我而言。
wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl; wcout.clear(); return TRUE;
而且我知道这个问题已经有一年了,但是回答永远不会太迟。
它(正如我所假设的)完全不是EnumWindows
的问题。 问题在于输出流。
在调试的时候,我注意到enumWindowsProc
对于每个窗口都被调用,但是一些迭代不会产生输出。
目前,我切换到使用_tprintf
,但我不明白原来的代码是什么问题。 调用wcout.flush()
也没有理想的效果。
Windows的文档(不知道它的准确性)说,EnumWindows只能枚举顶层窗口。 如果你想枚举子窗口,你需要使用EnumChildWindows函数,你必须通过父窗口的处理