// Test_hook.cpp: defines the console application Program . // # Include "stdafx. H "# include <windows. h> # include <stdio. h> # include <stdarg. h> # include <ctype. h> # include <winerror. h> // some global variableshinstance g_instance; // handler of current instancehhook g_hook; // handler of hookbool sethook (); bool unsethook (); // The hook function (will be called by other processes) Static lresult callback keyboardproc (INT ncode, wparam, lparam );////////// //////////////////////////////////////// /// // Odprintf -- debug functionvoid _ cdecl odprintf (const char * FMT, ...) {char Buf [4096], * P = Buf; va_list ARGs; va_start (ARGs, FMT); P + = vsnprintf_s (p, sizeof (BUF), _ truncate, FMT, ARGs); va_end (ARGs); While (P> Buf & isspace (P [-1]) * -- p = '\ 0 '; * P ++ = '\ R'; * P ++ =' \ n'; * P = '\ 0'; outputdebugstringa (BUF ); // output as ANSI string // outputde Bugstring} lresult callback keyboardproc (INT ncode, wparam, lparam) {KBDLLHOOKSTRUCT * PKH = (KBDLLHOOKSTRUCT *) lparam; // hc_action: the wparam and lparam parameters contain the IF (ncode = hc_action) {If (: getasynckeystate ('1') & 0x8000) {odprintf ("111111111111111111");} // specifies the status of the virtual key when the function is called // bool bctrlkey =: getasynckeystate (vk_control) & 0x8000; bool bctrlkey =:: getasynckeystate (vk_control)> (sizeof (short )* 8)-1); If (PKH-> vkcode = vk_escape & bctrlkey) | // Ctrl + ESC Start Menu (PKH-> vkcode = vk_tab & PKH-> flags & llkhf_altdown) | // Alt + TAB screen switching menu (PKH-> vkcode = vk_escape & PKH-> flags & llkhf_altdown) | // Alt + ESC screen switching (PKH-> vkcode = vk_lwin | PKH-> vkcode = vk_rwin) // left and right windows keys) {odprintf ("OK... i'm come here! "); // This will appear twice, because return 1 ;}// call next hook in chainreturn: callnexthookex (g_hook, ncode, wparam, lparam );} bool sethook () {If (g_instance | g_hook) // already hooked! Return true; g_instance = (hinstance): getmodulehandle (null); g_hook =: setwindowshookex (wh_keyboard_ll, (hookproc) keyboardproc, g_instance, 0); If (! G_hook) {odprintf ("sethook error, error code = % lD",: getlasterror (); // error codereturn false;} return true; // Hook has been created correctly} bool unsethook () {If (g_hook) {// check if hook handler is valid: unhookwindowshookex (g_hook ); // unhook is done hereg_hook = NULL; // remove hook handler to avoid to use it again} return true; // Hook has been removed} int _ tmain (INT argc, _ tchar * argv []) {odprintf ("Test of keyboardproc, starting..."); If (! Sethook () Return-1; MSG; while (: getmessage (& MSG, null, 0, 0)> 0) {translatemessage (& MSG ); dispatchmessage (& MSG) ;}// clean: unsethook (); Return 0 ;}