win32

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

HWINEVENTHOOK  EventHook;

BOOL WINAPI HandlerRoutine(_In_ DWORD dwCtrlType)
{
    if (dwCtrlType == CTRL_CLOSE_EVENT)
    {
        UnhookWinEvent(EventHook);
    }
    return 1;
}

void __stdcall Wineventproc(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD idEventThread, DWORD dwmsEventTime)
{
    if (event == EVENT_SYSTEM_FOREGROUND)
    {
         if (IsWindowVisible(hwnd))
        {
            TCHAR title[512] = {};
            int index = GetWindowText(hwnd, title, 512);
            if (_tcsncmp(title, TEXT("Task Switching"), 14))
            {
                title[index] = L'
';
                title[index + 1] = L'';
                OutputDebugString(title);
            }
        }
    }
}

void SetHook()
{
    if (!(EventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, NULL, Wineventproc, 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS)))
    {
        int i = GetLastError();
        cout << "Failed to install MouseHook hook!   " << i << endl;
    }
}



int main()
{
    SetConsoleCtrlHandler(HandlerRoutine, 1);

    SetHook();
    MSG msg;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

EVENT_SYSTEM_FOREGROUND: 前台窗口更改时发送该事件。即使前景窗口已更改为同一线程中的另一个窗口,系统也会发送此事件。

原文地址:https://www.cnblogs.com/strive-sun/p/14291694.html