There is always a question: if someone else installs a keyboard hook on your computer to monitor your keyboard buttons, how can my program avoid monitoring these global keyboard hooks. recently, I have been studying hooks due to working relationships. By the way, I have studied this problem. Today I have found a solution.
Solution:
Install a local keyboard hook (thread-specified hook) in my program. The keyboard hook function does not call callnexthookex;
Principle:
1. The hook chain can be damaged. A hook of the same type will form a chain. If the first called Hook does not call callnexthookex, the subsequent hook will not be called.
2. for a specific thread, the thread hook is called before the system hook.
Lab:
Keyboard hook (wh_keyboard)
I wrote a simple dialog box program. Some code is as follows:
1. Declare hook hhook ghook = NULL first;
2. keyboard hook functions:
Lresult callback keyboardproc (INT ncode, wparam, lparam)
{
MessageBox (afxgetmainwnd ()-> getsafehwnd (), "thread hook", "keyboard", mb_ OK );
Return 0;
// Return callnexthookex (ghook, ncode, wparam, lparam );
}
3. Installation HOOK:
DWORD nthreadid = getcurrentthreadid ();
Ghook = setwindowshookex (wh_keyboard, keyboardproc, afxgetapp ()-> m_hinstance, nthreadid );
If (ghook = NULL)
{
Afxmessagebox ("Install keyboard hook failed", mb_ OK );
}
4. Uninstall the hook
Bool ret = unhookwindowshookex (ghook );
The experiment method is as follows:
1. Start another program, install the system keyboard hook, then start my program, and install a local keyboard hook. The experiment results show that the system hook is invalid for my program.
2. Start my program, install a local keyboard hook, and then start another program to install the system keyboard hook. The system keyboard hook in my program is invalid.