Visual-Vincent / InputHelper

A .NET friendly library for simulating mouse and keyboard input.
BSD 3-Clause "New" or "Revised" License
13 stars 6 forks source link

Could there be actions that "unhook" a local hook? #5

Closed JBB2020 closed 11 months ago

JBB2020 commented 3 years ago

Hello Vincent,

I hope that you are doing well!

Quick question: are there events or actions that could "unhook" a keyboard local hook? And is there a way to track a local keyboard hook's status?

While I'm still struggling to reproduce this, I ended up several times with the local keyboard hook not working anymore while I was using PPT for regular work. I found out that disposing of the local keyboard hook, and then recreating it, allows to make it work again. But I did not manage (yet) to understand what made the previous local keyboard hook not work anymore, and I would be curious to know what happened and how I can investigate.

Best,

JB

Visual-Vincent commented 3 years ago

Hi, Unfortunately there isn't much documentation or information out there regarding local hooks, so it's really difficult to tell what could cause them to get removed. Sadly there are also no simple/practical ways of checking if the hook is still attached or not as Microsoft does not expose any public API for that (there are a few undocumented function calls and structures that people have managed to find/reverse engineer that can be used for this purpose, but they're unreliable and prone to be changed at any time by MS).

Currently there are only two possible scenarios I can think of:

  1. The thread that the hook is attached to is terminated (P/Invoke GetCurrentThreadId() and log the returned ID every time you re-initialize the hook to see if it changes)
  2. The hook is removed due to a timeout

The latter is possible for global low-level keyboard hooks; if execution of a low-level hook takes longer than a couple of hundred milliseconds the OS will silently remove it so that mouse and keyboard input remains responsive. I don't know if this is also the case for local hooks, but as a rule of thumb try not to do long-running work in the hook events (KeyDown, KeyUp, etc.). If you need to do processing that may take a while, better to offload it to a Task.

Side note: From now on my replies should hopefully be a bit more frequent.