How might one invoke a callback whenever the current active window changes. I've seen how it might be done using CBTProc. However, global events aren't easy to hook into with managed code. I'm interested in finding a way that doesn't require polling. I'd prefer an event driven approach.
Regards
You can use
SetWinEventHook
and listen for theEVENT_SYSTEM_FOREGROUND
event. Use theWINEVENT_OUTOFCONTEXT
flag to avoid the global-hook problem.I know this thread is old, but for sake of future use: when running the code you'll notice a crash after a while. This is caused from the line in the Form constructor:
Instead of the above make the following modification:
..works now as expected!
Create a new windows forms project, add a textbox, make it multiline, and set the textbox Dock property to fill, name it Log and paste in the following code (you'll need to add System.Runtime.InteropServices to your usings)...