SetWinEventHook

Windows specific questions.
Post Reply
cvknippenberg
Posts: 2
Joined: Sep 30, 2022 6:49

SetWinEventHook

Post by cvknippenberg »

I would like to fire a callback sub when the focused app changes in Windows and tried to implement SetWinEventHook but apparently the callback is not started?
Any help would be appreciated.

Code: Select all

#include once "windows.bi"

Dim As HWINEVENTHOOK gHook

Sub CallBackFunction(hook As HWINEVENTHOOK, Event As DWORD, hwnd As HWND, idObject As Long, idChild As Long, dwEventThread As DWORD, dwmsEventTime As DWORD)
  	Print "CallBackFunction executed"
End Sub

gHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, Null, @CallBackFunction, 0, 0, WINEVENT_OUTOFCONTEXT Or WINEVENT_SKIPOWNPROCESS)
If gHook = 0 Then
	print "Call to SetWinEventHook failed with error is ";getlasterror()
Else
	Print "SetWinEventHook set"
endif
Sleep
SARG
Posts: 1755
Joined: May 27, 2005 7:15
Location: FRANCE

Re: SetWinEventHook

Post by SARG »

It took me a bit of time to understand that when sleep is executed nothing more can be executed in this program so obvioulsy also the callback.

After some search I found an example in this page : https://bitcoden.com/answers/setting-up ... s-messages


Just add these lines : after setevenhook(...)
a quick and raw way but normally needs a complete Windows message loop as written in the linked page

Code: Select all

messagebox(0,@"It works",0,MB_OK) ''allows the callback to work
And to be clean :

Code: Select all

UnhookWinEvent(ghook)  '<--- remove the hook
cvknippenberg
Posts: 2
Joined: Sep 30, 2022 6:49

Re: SetWinEventHook

Post by cvknippenberg »

Thanks for your quick help.
Post Reply