Question

I would like to know what's the best way, in term of efficiency (cpu/memory usage), to temporarily suspend/bypass a low level mouse/keyboard hook.

The current solution I found is to set a global var, "doHook" in the exemple, test it in the hook proc and if not set just let it pass with CallNextHookEx like that :

    if ((nCode < 0) || (!doHook))
    {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

Is it a good solution ? a better way ?

Thanks

Was it helpful?

Solution

You have 2 options:

  • Removing the hook entirely by calling UnhookWindowsHookEx.
  • Leaving the hook in place and skipping normal operation.

Low level keyboard and mouse hooks are somewhat costly, since they introduce additional context switches for handling input events:

The [...] hook is not injected into another process. Instead, the context switches back to the process that installed the hook and it is called in its original context. Then the context switches back to the application that generated the event.

Essentially, your do-nothing hook still uses up thousands of clock cycles for context switching, for all input events. To minimize overall impact you should consider uninstalling the hook entirely and reinstalling it when necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top