c++windowswinapiwindows-process

Filtering/Parsing list produced from EnumWindows in C++


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.


Solution

  • 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';
        }
    }