我在假设,我所问的实际上应该是默认值,但我遇到了一些我不理解的行为。
#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>
答案 0 :(得分:8)
好吧,wcout.flush()
永远不会有效,但wcout.clear()
修复了你的代码,至少对我而言。
wcout << hWnd << TEXT( ": " ) << windowTitle << std::endl;
wcout.clear();
return TRUE;
我知道这个问题已经有一年了,但是回答永远都不会太晚。
答案 1 :(得分:2)
(正如我所假设的那样)EnumWindows
根本不存在问题。问题出在输出流上。
在调试时,我注意到enumWindowsProc
被称为每个窗口都很好,但是有些迭代根本就没有生成输出。
暂时,我转而使用_tprintf
,但我不明白原始代码的问题是什么。调用wcout.flush()
也没有任何可取的效果。
答案 2 :(得分:1)
这是一个列出所有打开的窗口的回调函数:
#include <string>
#include <iostream>
#include <Windows.h>
static BOOL CALLBACK enumWindowCallback(HWND hWnd, LPARAM lparam) {
int length = GetWindowTextLength(hWnd);
char* buffer = new char[length + 1];
GetWindowText(hWnd, buffer, length + 1);
std::string windowTitle(buffer);
// Ignore windows if invisible or missing a title
if (IsWindowVisible(hWnd) && length != 0) {
std::cout << hWnd << ": " << windowTitle << std::endl;
}
return TRUE;
}
int main() {
std::cout << "Enmumerating windows..." << std::endl;
EnumWindows(enumWindowCallback, NULL);
std::cin.ignore();
return 0;
}
如果要检查窗口是否已最小化,可以使用IsIconic()
。
另请参见:
答案 3 :(得分:-1)
Windows的文档(dunno其准确性)表示EnumWindows仅枚举顶级窗口。如果你想枚举子窗口,你需要使用EnumChildWindows函数,你必须传递父窗口的句柄