Youtube interaction with WINAPI GetForegroundWindow()?

时间:2015-05-04 19:51:51

标签: c++ winapi youtube

I'm getting a weird interaction with YouTube and a simple program that gets the window title of a window: My small code is here:

#include <Windows.h>
#include <tchar.h>
#include <iostream>
#include <string>

wstring getWindowTitle()
{
    // stores the program title
    wstring title;
    // handle to the window
    HWND handle = GetForegroundWindow();
    // length of the title
    int len = GetWindowTextLengthW(handle) + 1;
    // programs title
    wchar_t * programTitle = new wchar_t[len];
    // gets the window title
    GetWindowTextW(handle, programTitle, len);
    // adds program title to our w string to store it in
    title += programTitle;
    return title;
}

int main()
{
    wstring windowTitle;
    windowTitle = L"Title is: ";
    while (1)
{
    windowTitle = getWindowTitle();
    std::wcout << windowTitle << endl;
    Sleep(3000);
}
    return 0;
}

It works as long as a youtube video isn't playing. For example this is a command line text i have:

C:\Windows\system32\cmd.exe
Mozilla Firefox Start Page - Mozilla Firefox
YouTube - Mozilla Firefox
McDonalds Artisan Grilled Chicken Sandwich? FAIL! - YouTube - Mozilla Firefox

After i open the youtube video it won't keep update the window title anymore, it will just stay there frozen, is it something with youtube/flash player bugging up GetForegroundWindow?

1 个答案:

答案 0 :(得分:1)

包括其他标题:

#include <io.h>
#include <fcntl.h>

并在main函数中的以下行之前:

std::wcout << windowTitle << endl;

添加以下内容:

_setmode(_fileno(stdout), _O_U16TEXT);

主要问题(而不是代码中唯一的问题)是wcout在内部处理某些Unicode字符的方式。因此,当您的应用程序在前台窗口中遇到某个Unicode字符时,它会停止执行。它与YouTube或您的Flash播放器无关。在控制台应用程序中阅读Unicode和Unicode。