Show a list of applications like alt-tab in Win7

1.4k views Asked by At

I am trying to print a list of running applications like alt-tab would give me. Here are what I have done so far:

1.In the beginning I tried EnumWindows, but I got hundreds of entries.

2.I found some similar questions and they led me to the blog of Raymond Chen. http://blogs.msdn.com/b/oldnewthing/archive/2007/10/08/5351207.aspx

However it still shows more than 100 windows(window_num1 being 158 and window_num2 being 329), while alt-tab would give me only 4. What did I do wrong? Here is my code:

#include <windows.h>
#include <tchar.h>
#include <iostream>
using namespace std;

#pragma comment(lib, "user32.lib")

HWND windowHandle;
int window_num1=0;
int window_num2=0;

BOOL IsAltTabWindow(HWND hwnd)
{
    if (hwnd == GetShellWindow())   //Desktop
        return false;
    // Start at the root owner
    HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);

    // See if we are the last active visible popup
    HWND hwndTry;
    while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry) 
    {
        if (IsWindowVisible(hwndTry)) 
            break;
        hwndWalk = hwndTry;
    }
    return hwndWalk == hwnd;
}

BOOL CALLBACK MyEnumProc(HWND hWnd, LPARAM lParam)
{
    TCHAR title[500];
    ZeroMemory(title, sizeof(title));

    //string strTitle;

    GetWindowText(hWnd, title, sizeof(title)/sizeof(title[0]));

    if (IsAltTabWindow(hWnd))
    {
        _tprintf(_T("Value is %s\n"), title);
        window_num1++;
    }
    window_num2++;

    //strTitle += title; // Convert to std::string
    if(_tcsstr(title, _T("Excel")))
    {
        windowHandle = hWnd;
        return FALSE;
    }
    return TRUE;
}

void MyFunc(void) //(called by main)
{
    EnumWindows(MyEnumProc, 0);
}

int main() 
{
    MyFunc();
    cout<<endl<<window_num1<<endl<<window_num2;
    return 0;
}
2

There are 2 answers

1
xMRi On BEST ANSWER

You failure is, that you should walk only visible windows... read the blog again.

For each visible window, walk up its owner chain until you find the root owner. Then walk back down the visible last active popup chain until you find a visible window. If you're back to where you're started, then put the window in the Alt+↹Tab list.

Your code walks over every window!

1
hyun On

Just use IsWindowVisible

BOOL CALLBACK MyEnumProc(HWND hWnd, LPARAM lParam)
{
    TCHAR title[256] = {0,};
    if (IsWindowVisible(hWnd) && GetWindowTextLength(hWnd) > 0)
    {
       window_num1++;
       GetWindowText(hWnd, title, _countof(title));
       _tprintf(_T("Value is %d, %s\n"), window_num1, title);
    }
    return TRUE;
 }