代码片段: 枚举桌面顶层窗口(在任务管理器中出现的)

陪她去流浪 桃子 2015年09月05日 阅读次数:2435

以下代码应该能列出你能够在“任务管理器”中所能看到的程序列表~

#include <cstdio>
#include <windows.h>

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 buf[1024];
        buf[GetWindowText(hwnd, buf, _countof(buf))] = '\0';
        printf("%08X - %s\n", hwnd, buf);
    }
    return TRUE;
}

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

这篇文章的内容已被作者标记为“过时”/“需要更新”/“不具参考意义”。

标签:代码片段 · WinAPI