FindWindow() doesn't find my window [C++]

Rob picture Rob · Jun 1, 2012 · Viewed 15.2k times · Source

This is not a complex question. I'm having trouble finding the handle that belongs to iTunes. But although iTunes is running in the background, it keeps telling me it can't find the window. So I went on checking whether I miss typed the window name, but spy++ pointed out to me that I was using the correct window name and class name (see below). I'm sure it's a small mistake but I can't seem to find it. Does anyone have an insight? Thanks in advance.

        HWND hwnd;
        hwnd = FindWindow((LPCWSTR)"iTunes",(LPCWSTR)"iTunes");
    if (hwnd != 0){
        cout << "WINDOW FOUND" << endl;
    } else { 
        cout << "WINDOW NOT FOUND" << endl; 
        cout << hwnd << endl;
    }

Answer

3Doubloons picture 3Doubloons · Jun 1, 2012

You are using ANSI strings with what appears to be the Unicode version of FindWindow.

Many Win32 functions are actually a pair of function and a macro. For example, FindWindow is defined approximately like this:

HWND WINAPI FindWindowA(LPCSTR lpClassName, LPCSTR lpWindowName);
HWND WINAPI FindWindowW(LPCWSTR lpClassName, LPCWSTR lpWindowName);

#if (UNICODE)
#  define FindWindow FindWindowW
#else
#  define FindWindow FindWindowA
#endif

Try explicitely calling FindWindowA or using wide strings like this:

HWND hwnd = FindWindow(L"iTunes", L"iTunes");