Using system; Using system. Collections. Generic; Using system. componentmodel; Using system. Data; Using system. drawing; Using system. text; Using system. reflection; Using system. runtime. interopservices; Using system. Windows. forms;Namespace wa_hooktest { Public partial class form1: Form { Public form1 () { Initializecomponent (); } Internal Enum hooktype // enumeration, hook type { // Msgfilter =-1, // Journalrecord = 0, // Journalplayback = 1, Keyboard = 2, // Getmessage = 3, // CALLWNDPROC = 4, // CBT = 5, // Sysmsgfilter = 6, // Mouse = 7, // Hardware = 8, // DEBUG = 9, // Shell = 10, // Foregroundidle = 11, // Callwndprocret = 12, Keyboardll = 13, // Mousell = 14, }; [Dllimport ("kernel32.dll")] Static extern int getcurrentthreadid (); // obtain the ID of the current thread [Dllimport ("user32.dll")] Internal extern static void unhookwindowshookex (intptr handle); // cancel the HOOK API [Dllimport ("user32.dll")] Internal extern static intptr setwindowshookex (INT idhook, [financialas (unmanagedtype. functionptr)] hookproc lpfn, intptr hinstance, int threadid); // sets the HOOK API [Dllimport ("user32.dll")] Internal extern static intptr callnexthookex (intptr handle, int code, intptr wparam, intptr lparam); // obtain the next HOOK API Intptr _ nexthookptr; // record the hook number Public Delegate intptr hookproc (INT code, intptr wparam, intptr lparam ); Public intptr myhookproc (INT code, intptr wparam, intptr lparam) { If (Code <0) { Return callnexthookex (_ nexthookptr, code, wparam, lparam ); } // Return, let the subsequent program process the message If (wparam. toint32 () = 98 | wparam. toint32 () = 66) {// If the user inputs B This. textbox1.text = ""; Return (intptr) 1; // The message is returned directly, and the processing is complete. } Else { Return intptr. Zero; // return, let the subsequent program process the message }
// If (wparam. toint32 () = 91) //{ // Return (intptr) 1; //} // Else { // Return intptr. zero; //} } Public void sethook () { If (_ nexthookptr! = Intptr. Zero) // already checked Return; // Thread hook Hookproc myhookproc = new hookproc (myhookproc); // declare a delegate object of your own hook implementation function // _ Nexthookptr = setwindowshookex (INT) hooktype. keyboard, myhookproc, intptr. Zero, getcurrentthreadid (); // Add it to the hook chain // Global hook _ Nexthookptr = setwindowshookex (INT) hooktype. keyboardll, myhookproc, Marshal. gethinstance (assembly. getexecutingassembly (). getmodules () [0]), 0); // Add it to the hook chain MessageBox. Show (_ nexthookptr. tostring ()); } Public void unhook () { If (_ nexthookptr! = Intptr. Zero) { Unhookwindowshookex (_ nexthookptr); // cancel from the hook chain _ Nexthookptr = intptr. zero; } } Private void form1_load (Object sender, eventargs E) { Sethook (); } Private void form=formclosing (Object sender, formclosingeventargs E) { Unhook (); } } } |