Filtering/Parsing list produced from EnumWindows in C++

天涯浪子 提交于 2019-12-11 08:42:11

问题


I am using the following code to get a list of windows running on my machine

#include <iostream>
#include <windows.h>

using namespace std;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    TCHAR buffer[512];
    SendMessage(hwnd, WM_GETTEXT, 512, (LPARAM)(void*)buffer);
    wcout << buffer << endl;
    return TRUE;
}

int main()
{
    EnumWindows(EnumWindowsProc, NULL);
    return 0;
}

I want to get a list of what is normally refered to as a Window - I say this because when running the above code I get a list of around 40 entries, most of these are not what I would call windows.

Here is an excerpt of the output produced by running the above script on my machine, out of the 5 entries only Microsoft Visual Studio is a Window

...
Task Switching
Microsoft Visual Studio
CiceroUIWndFrame

Battery Meter

Network Flyout
...

How can I go about filtering/parsing this data, as there is not anything to use as an identifier.


回答1:


I would use EnumDesktopWindows to enumerate all top-level windows in your desktop; you may even use the IsWindowsVisible API during the enumeration process, to filter non-visible windows out.

This compilable C++ code works fine for me (note that here I showed how to pass some additional info to the enumeration proc, in this case using a pointer to a vector<wstring>, in which the window titles are stored for later processing):

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using std::vector;
using std::wcout;
using std::wstring;

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    if (!IsWindowVisible(hwnd))
    {
        return TRUE;
    }

    wchar_t titleBuf[512];
    if (GetWindowText(hwnd, titleBuf, _countof(titleBuf)) > 0)
    {
        auto pTitles = reinterpret_cast<vector<wstring>*>(lParam);
        pTitles->push_back(titleBuf);
    }

    return TRUE;
}

int main()
{
    vector<wstring> titles;
    EnumDesktopWindows(nullptr, EnumWindowsProc, reinterpret_cast<LPARAM>(&titles));

    for (const auto& s : titles)
    {
        wcout << s << L'\n';
    }
}



回答2:


Define what you call a Window and query the windows handle for the correct properties. Use GetWindowLong() with for example GWL_HWNDPARENT to test if there's no parent window or if the parent window is the desktop window. Additional test may be needed, e.g. you can use the (extended) window styles. See also here for additional ideas on usable tests.



来源:https://stackoverflow.com/questions/41619886/filtering-parsing-list-produced-from-enumwindows-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!