0
#define UNICODE
#define _UNICODE
#include <iostream>
#include <Windows.h>
#include <fstream>
using namespace std;

void CALLBACK Wineventproc(HWINEVENTHOOK hWinEventHook,DWORD event,
        HWND hwnd,
        LONG idObject,
        LONG idChild,
        DWORD idEventThread,
        DWORD dwmsEventTime
){
    cout<<"EventId:"<<idEventThread<<endl;
}
int main() {
    CoInitialize(nullptr);
    HWINEVENTHOOK hEventHook = SetWinEventHook(EVENT_SYSTEM_SWITCHSTART, EVENT_SYSTEM_SWITCHEND, nullptr, Wineventproc, 0, 0,
                                               WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
    if(hEventHook==NULL){
        cout<<"hook fail"<<endl;
        return 0;
    }
    MSG mess;
    BOOL  bRet;
    cout<<"1"<<endl;
    while ((bRet=GetMessage(&mess, nullptr,0,0))!=0){
        cout<<"2"<<endl;
        if(bRet == -1){
        }else {
            TranslateMessage(&mess);
            DispatchMessage(&mess);
        }
    }
    if(!UnhookWinEvent(hEventHook)){
        return 0;
    }
    CoUninitialize();
    return 0;
}

Just an easy demo that I want to use SetWinEventHook() to get program switch event. But, when I input Alt+Tab (EVENT_SYSTEM_SWITCHSTART), the GetMessage() is still blocked. What's wrong?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • this is because `EVENT_SYSTEM_SWITCHSTART` sent by csrss, when it handle alt+tab. but if another process register this hot key - no `EVENT_SYSTEM_SWITCHSTART` event. explorer.exe register alt+tab handler. if during alt+tab message explorer view that it under debugger - it remove hot key. after this again csrss handle this and `EVENT_SYSTEM_SWITCHSTART` will be – RbMm Jun 02 '22 at 12:27
  • @RbMm Is that mean `EVENT_SYSTEM_SWITCHSTART` always won't work ? –  Jun 02 '22 at 14:09
  • in modern systems - in practic yes. the explorer will be handle alt+tab. if want you can test what i say - attach debugger to explorer. press alt+tab. that you can see that alt+tab select ui is changed to more classic (this is csrss handler) and you code begin work – RbMm Jun 02 '22 at 14:35
  • https://stackoverflow.com/questions/49588438/the-system-events-event-system-switchstart-and-event-system-switchend-works-in-w – Hans Passant Jun 02 '22 at 14:48

1 Answers1

0

Finally, I change to use EVENT_SYSTEM_FOREGROUND .