C#键盘鼠标钩子实例
本文实例讲述了C#键盘鼠标钩子的实现方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Runtime.InteropServices; usingSystem.ComponentModel; usingSystem.Reflection;
namespaceAlif.CommonAPI.WindowsAPI { ///<summary> ///用户键盘鼠标钩子 ///</summary> publicclassUserActivityHook { #regionWindowsstructuredefinitions
///<summary> ///ThePOINTstructuredefinesthex-andy-coordinatesofapoint. ///</summary> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp ///</remarks> [StructLayout(LayoutKind.Sequential)] privateclassPOINT { ///<summary> ///Specifiesthex-coordinateofthepoint. ///</summary> publicintx; ///<summary> ///Specifiesthey-coordinateofthepoint. ///</summary> publicinty; }
///<summary> ///TheMOUSEHOOKSTRUCTstructurecontainsinformationaboutamouseeventpassedtoaWH_MOUSEhookprocedure,MouseProc. ///</summary> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp ///</remarks> [StructLayout(LayoutKind.Sequential)] privateclassMouseHookStruct { ///<summary> ///SpecifiesaPOINTstructurethatcontainsthex-andy-coordinatesofthecursor,inscreencoordinates. ///</summary> publicPOINTpt; ///<summary> ///Handletothewindowthatwillreceivethemousemessagecorrespondingtothemouseevent. ///</summary> publicinthwnd; ///<summary> ///Specifiesthehit-testvalue.Foralistofhit-testvalues,seethedescriptionoftheWM_NCHITTESTmessage. ///</summary> publicintwHitTestCode; ///<summary> ///Specifiesextrainformationassociatedwiththemessage. ///</summary> publicintdwExtraInfo; }
///<summary> ///TheMSLLHOOKSTRUCTstructurecontainsinformationaboutalow-levelkeyboardinputevent. ///</summary> [StructLayout(LayoutKind.Sequential)] privateclassMouseLLHookStruct { ///<summary> ///SpecifiesaPOINTstructurethatcontainsthex-andy-coordinatesofthecursor,inscreencoordinates. ///</summary> publicPOINTpt; ///<summary> ///IfthemessageisWM_MOUSEWHEEL,thehigh-orderwordofthismemberisthewheeldelta. ///Thelow-orderwordisreserved.Apositivevalueindicatesthatthewheelwasrotatedforward, ///awayfromtheuser;anegativevalueindicatesthatthewheelwasrotatedbackward,towardtheuser. ///OnewheelclickisdefinedasWHEEL_DELTA,whichis120. ///IfthemessageisWM_XBUTTONDOWN,WM_XBUTTONUP,WM_XBUTTONDBLCLK,WM_NCXBUTTONDOWN,WM_NCXBUTTONUP, ///orWM_NCXBUTTONDBLCLK,thehigh-orderwordspecifieswhichXbuttonwaspressedorreleased, ///andthelow-orderwordisreserved.Thisvaluecanbeoneormoreofthefollowingvalues.Otherwise,mouseDataisnotused. ///XBUTTON1 ///ThefirstXbuttonwaspressedorreleased. ///XBUTTON2 ///ThesecondXbuttonwaspressedorreleased. ///</summary> publicintmouseData; ///<summary> ///Specifiestheevent-injectedflag.Anapplicationcanusethefollowingvaluetotestthemouseflags.ValuePurpose ///LLMHF_INJECTEDTesttheevent-injectedflag. ///0 ///Specifieswhethertheeventwasinjected.Thevalueis1iftheeventwasinjected;otherwise,itis0. ///1-15 ///Reserved. ///</summary> publicintflags; ///<summary> ///Specifiesthetimestampforthismessage. ///</summary> publicinttime; ///<summary> ///Specifiesextrainformationassociatedwiththemessage. ///</summary> publicintdwExtraInfo; }
///<summary> ///TheKBDLLHOOKSTRUCTstructurecontainsinformationaboutalow-levelkeyboardinputevent. ///</summary> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp ///</remarks> [StructLayout(LayoutKind.Sequential)] privateclassKeyboardHookStruct { ///<summary> ///Specifiesavirtual-keycode.Thecodemustbeavalueintherange1to254. ///</summary> publicintvkCode; ///<summary> ///Specifiesahardwarescancodeforthekey. ///</summary> publicintscanCode; ///<summary> ///Specifiestheextended-keyflag,event-injectedflag,contextcode,andtransition-stateflag. ///</summary> publicintflags; ///<summary> ///Specifiesthetimestampforthismessage. ///</summary> publicinttime; ///<summary> ///Specifiesextrainformationassociatedwiththemessage. ///</summary> publicintdwExtraInfo; } #endregion
#regionWindowsfunctionimports ///<summary> ///TheSetWindowsHookExfunctioninstallsanapplication-definedhookprocedureintoahookchain. ///Youwouldinstallahookproceduretomonitorthesystemforcertaintypesofevents.Theseevents ///areassociatedeitherwithaspecificthreadorwithallthreadsinthesamedesktopasthecallingthread. ///</summary> ///<paramname="idHook"> ///[in]Specifiesthetypeofhookproceduretobeinstalled.Thisparametercanbeoneofthefollowingvalues. ///</param> ///<paramname="lpfn"> ///[in]Pointertothehookprocedure.IfthedwThreadIdparameteriszeroorspecifiestheidentifierofa ///threadcreatedbyadifferentprocess,thelpfnparametermustpointtoahookprocedureinadynamic-link ///library(DLL).Otherwise,lpfncanpointtoahookprocedureinthecodeassociatedwiththecurrentprocess. ///</param> ///<paramname="hMod"> ///[in]HandletotheDLLcontainingthehookprocedurepointedtobythelpfnparameter. ///ThehModparametermustbesettoNULLifthedwThreadIdparameterspecifiesathreadcreatedby ///thecurrentprocessandifthehookprocedureiswithinthecodeassociatedwiththecurrentprocess. ///</param> ///<paramname="dwThreadId"> ///[in]Specifiestheidentifierofthethreadwithwhichthehookprocedureistobeassociated. ///Ifthisparameteriszero,thehookprocedureisassociatedwithallexistingthreadsrunninginthe ///samedesktopasthecallingthread. ///</param> ///<returns> ///Ifthefunctionsucceeds,thereturnvalueisthehandletothehookprocedure. ///Ifthefunctionfails,thereturnvalueisNULL.Togetextendederrorinformation,callGetLastError. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp ///</remarks> [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall,SetLastError=true)] privatestaticexternintSetWindowsHookEx( intidHook, HookProclpfn, IntPtrhMod, intdwThreadId);
///<summary> ///TheUnhookWindowsHookExfunctionremovesahookprocedureinstalledinahookchainbytheSetWindowsHookExfunction. ///</summary> ///<paramname="idHook"> ///[in]Handletothehooktoberemoved.ThisparameterisahookhandleobtainedbyapreviouscalltoSetWindowsHookEx. ///</param> ///<returns> ///Ifthefunctionsucceeds,thereturnvalueisnonzero. ///Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp ///</remarks> [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall,SetLastError=true)] privatestaticexternintUnhookWindowsHookEx(intidHook);
///<summary> ///TheCallNextHookExfunctionpassesthehookinformationtothenexthookprocedureinthecurrenthookchain. ///Ahookprocedurecancallthisfunctioneitherbeforeorafterprocessingthehookinformation. ///</summary> ///<paramname="idHook">Ignored.</param> ///<paramname="nCode"> ///[in]Specifiesthehookcodepassedtothecurrenthookprocedure. ///Thenexthookprocedureusesthiscodetodeterminehowtoprocessthehookinformation. ///</param> ///<paramname="wParam"> ///[in]SpecifiesthewParamvaluepassedtothecurrenthookprocedure. ///Themeaningofthisparameterdependsonthetypeofhookassociatedwiththecurrenthookchain. ///</param> ///<paramname="lParam"> ///[in]SpecifiesthelParamvaluepassedtothecurrenthookprocedure. ///Themeaningofthisparameterdependsonthetypeofhookassociatedwiththecurrenthookchain. ///</param> ///<returns> ///Thisvalueisreturnedbythenexthookprocedureinthechain. ///Thecurrenthookproceduremustalsoreturnthisvalue.Themeaningofthereturnvaluedependsonthehooktype. ///Formoreinformation,seethedescriptionsoftheindividualhookprocedures. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp ///</remarks> [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] privatestaticexternintCallNextHookEx( intidHook, intnCode, intwParam, IntPtrlParam);
///<summary> ///TheCallWndProchookprocedureisanapplication-definedorlibrary-definedcallback ///functionusedwiththeSetWindowsHookExfunction.TheHOOKPROCtypedefinesapointer ///tothiscallbackfunction.CallWndProcisaplaceholderfortheapplication-defined ///orlibrary-definedfunctionname. ///</summary> ///<paramname="nCode"> ///[in]Specifieswhetherthehookproceduremustprocessthemessage. ///IfnCodeisHC_ACTION,thehookproceduremustprocessthemessage. ///IfnCodeislessthanzero,thehookproceduremustpassthemessagetothe ///CallNextHookExfunctionwithoutfurtherprocessingandmustreturnthe ///valuereturnedbyCallNextHookEx. ///</param> ///<paramname="wParam"> ///[in]Specifieswhetherthemessagewassentbythecurrentthread. ///Ifthemessagewassentbythecurrentthread,itisnonzero;otherwise,itiszero. ///</param> ///<paramname="lParam"> ///[in]PointertoaCWPSTRUCTstructurethatcontainsdetailsaboutthemessage. ///</param> ///<returns> ///IfnCodeislessthanzero,thehookproceduremustreturnthevaluereturnedbyCallNextHookEx. ///IfnCodeisgreaterthanorequaltozero,itishighlyrecommendedthatyoucallCallNextHookEx ///andreturnthevalueitreturns;otherwise,otherapplicationsthathaveinstalledWH_CALLWNDPROC ///hookswillnotreceivehooknotificationsandmaybehaveincorrectlyasaresult.Ifthehook ///proceduredoesnotcallCallNextHookEx,thereturnvalueshouldbezero. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp ///</remarks> privatedelegateintHookProc(intnCode,intwParam,IntPtrlParam);
///<summary> ///TheToAsciifunctiontranslatesthespecifiedvirtual-keycodeandkeyboard ///statetothecorrespondingcharacterorcharacters.Thefunctiontranslatesthecode ///usingtheinputlanguageandphysicalkeyboardlayoutidentifiedbythekeyboardlayouthandle. ///</summary> ///<paramname="uVirtKey"> ///[in]Specifiesthevirtual-keycodetobetranslated. ///</param> ///<paramname="uScanCode"> ///[in]Specifiesthehardwarescancodeofthekeytobetranslated. ///Thehigh-orderbitofthisvalueissetifthekeyisup(notpressed). ///</param> ///<paramname="lpbKeyState"> ///[in]Pointertoa256-bytearraythatcontainsthecurrentkeyboardstate. ///Eachelement(byte)inthearraycontainsthestateofonekey. ///Ifthehigh-orderbitofabyteisset,thekeyisdown(pressed). ///Thelowbit,ifset,indicatesthatthekeyistoggledon.Inthisfunction, ///onlythetogglebitoftheCAPSLOCKkeyisrelevant.Thetogglestate ///oftheNUMLOCKandSCROLLLOCKkeysisignored. ///</param> ///<paramname="lpwTransKey"> ///[out]Pointertothebufferthatreceivesthetranslatedcharacterorcharacters. ///</param> ///<paramname="fuState"> ///[in]Specifieswhetheramenuisactive.Thisparametermustbe1ifamenuisactive,or0otherwise. ///</param> ///<returns> ///Ifthespecifiedkeyisadeadkey,thereturnvalueisnegative.Otherwise,itisoneofthefollowingvalues. ///ValueMeaning ///0Thespecifiedvirtualkeyhasnotranslationforthecurrentstateofthekeyboard. ///1Onecharacterwascopiedtothebuffer. ///2Twocharacterswerecopiedtothebuffer.Thisusuallyhappenswhenadead-keycharacter ///(accentordiacritic)storedinthekeyboardlayoutcannotbecomposedwiththespecified ///virtualkeytoformasinglecharacter. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp ///</remarks> [DllImport("user32")] privatestaticexternintToAscii( intuVirtKey, intuScanCode, byte[]lpbKeyState, byte[]lpwTransKey, intfuState);
///<summary> ///TheGetKeyboardStatefunctioncopiesthestatusofthe256virtualkeystothe ///specifiedbuffer. ///</summary> ///<paramname="pbKeyState"> ///[in]Pointertoa256-bytearraythatcontainskeyboardkeystates. ///</param> ///<returns> ///Ifthefunctionsucceeds,thereturnvalueisnonzero. ///Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError. ///</returns> ///<remarks> ///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp ///</remarks> [DllImport("user32")] privatestaticexternintGetKeyboardState(byte[]pbKeyState);
[DllImport("user32.dll",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] privatestaticexternshortGetKeyState(intvKey);
#endregion
#regionWindowsconstants
//valuesfromWinuser.hinMicrosoftSDK. ///<summary> ///WindowsNT/2000/XP:Installsahookprocedurethatmonitorslow-levelmouseinputevents. ///</summary> privateconstintWH_MOUSE_LL=14; ///<summary> ///WindowsNT/2000/XP:Installsahookprocedurethatmonitorslow-levelkeyboard inputevents. ///</summary> privateconstintWH_KEYBOARD_LL=13;
///<summary> ///Installsahookprocedurethatmonitorsmousemessages.Formoreinformation,seetheMouseProchookprocedure. ///</summary> privateconstintWH_MOUSE=7; ///<summary> ///Installsahookprocedurethatmonitorskeystrokemessages.Formoreinformation,seetheKeyboardProchookprocedure. ///</summary> privateconstintWH_KEYBOARD=2;
///<summary> ///TheWM_MOUSEMOVEmessageispostedtoawindowwhenthecursormoves. ///</summary> privateconstintWM_MOUSEMOVE=0x200; ///<summary> ///TheWM_LBUTTONDOWNmessageispostedwhentheuserpressestheleftmousebutton ///</summary> privateconstintWM_LBUTTONDOWN=0x201; ///<summary> ///TheWM_RBUTTONDOWNmessageispostedwhentheuserpressestherightmousebutton ///</summary> privateconstintWM_RBUTTONDOWN=0x204; ///<summary> ///TheWM_MBUTTONDOWNmessageispostedwhentheuserpressesthemiddlemousebutton ///</summary> privateconstintWM_MBUTTONDOWN=0x207; ///<summary> ///TheWM_LBUTTONUPmessageispostedwhentheuserreleasestheleftmousebutton ///</summary> privateconstintWM_LBUTTONUP=0x202; ///<summary> ///TheWM_RBUTTONUPmessageispostedwhentheuserreleasestherightmousebutton ///</summary> privateconstintWM_RBUTTONUP=0x205; ///<summary> ///TheWM_MBUTTONUPmessageispostedwhentheuserreleasesthemiddlemousebutton ///</summary> privateconstintWM_MBUTTONUP=0x208; ///<summary> ///TheWM_LBUTTONDBLCLKmessageispostedwhentheuserdouble-clickstheleftmousebutton ///</summary> privateconstintWM_LBUTTONDBLCLK=0x203; ///<summary> ///TheWM_RBUTTONDBLCLKmessageispostedwhentheuserdouble-clickstherightmousebutton ///</summary> privateconstintWM_RBUTTONDBLCLK=0x206; ///<summary> ///TheWM_RBUTTONDOWNmessageispostedwhentheuserpressestherightmousebutton ///</summary> privateconstintWM_MBUTTONDBLCLK=0x209; ///<summary> ///TheWM_MOUSEWHEELmessageispostedwhentheuserpressesthemousewheel. ///</summary> privateconstintWM_MOUSEWHEEL=0x020A;
///<summary> ///TheWM_KEYDOWNmessageispostedtothewindowwiththekeyboardfocuswhenanonsystem ///keyispressed.AnonsystemkeyisakeythatispressedwhentheALTkeyisnotpressed. ///</summary> privateconstintWM_KEYDOWN=0x100; ///<summary> ///TheWM_KEYUPmessageispostedtothewindowwiththekeyboardfocuswhenanonsystem ///keyisreleased.AnonsystemkeyisakeythatispressedwhentheALTkeyisnotpressed, ///orakeyboardkeythatispressedwhenawindowhasthekeyboardfocus. ///</summary> privateconstintWM_KEYUP=0x101; ///<summary> ///TheWM_SYSKEYDOWNmessageispostedtothewindowwiththekeyboardfocuswhentheuser ///pressestheF10key(whichactivatesthemenubar)orholdsdowntheALTkeyandthen ///pressesanotherkey.Italsooccurswhennowindowcurrentlyhasthekeyboardfocus; ///inthiscase,theWM_SYSKEYDOWNmessageissenttotheactivewindow.Thewindowthat ///receivesthemessagecandistinguishbetweenthesetwocontextsbycheckingthecontext ///codeinthelParamparameter. ///</summary> privateconstintWM_SYSKEYDOWN=0x104; ///<summary> ///TheWM_SYSKEYUPmessageispostedtothewindowwiththekeyboardfocuswhentheuser ///releasesakeythatwaspressedwhiletheALTkeywashelddown.Italsooccurswhenno ///windowcurrentlyhasthekeyboardfocus;inthiscase,theWM_SYSKEYUPmessageissent ///totheactivewindow.Thewindowthatreceivesthemessagecandistinguishbetween ///thesetwocontextsbycheckingthecontextcodeinthelParamparameter. ///</summary> privateconstintWM_SYSKEYUP=0x105;
privateconstbyteVK_SHIFT=0x10; privateconstbyteVK_CAPITAL=0x14; privateconstbyteVK_NUMLOCK=0x90;
#endregion
///<summary> ///CreatesaninstanceofUserActivityHookobjectandsetsmouseandkeyboardhooks. ///</summary> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> publicUserActivityHook() { Start(); }
///<summary> ///CreatesaninstanceofUserActivityHookobjectandinstallsbothoroneofmouseand/orkeyboardhooksandstartsrasingevents ///</summary> ///<paramname="InstallMouseHook"><b>true</b>ifmouseeventsmustbemonitored</param> ///<paramname="InstallKeyboardHook"><b>true</b>ifkeyboardeventsmustbemonitored</param> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> ///<remarks> ///TocreateaninstancewithoutinstallinghookscallnewUserActivityHook(false,false) ///</remarks> publicUserActivityHook(boolInstallMouseHook,boolInstallKeyboardHook) { Start(InstallMouseHook,InstallKeyboardHook); }
///<summary> ///Destruction. ///</summary> ~UserActivityHook() { //uninstallhooksanddonotthrowexceptions Stop(true,true,false); }
///<summary> ///Occurswhentheusermovesthemouse,pressesanymousebuttonorscrollsthewheel ///</summary> publiceventMouseEventHandlerOnMouseActivity; ///<summary> ///Occurswhentheuserpressesakey ///</summary> publiceventKeyEventHandlerKeyDown; ///<summary> ///Occurswhentheuserpressesandreleases ///</summary> publiceventKeyPressEventHandlerKeyPress; ///<summary> ///Occurswhentheuserreleasesakey ///</summary> publiceventKeyEventHandlerKeyUp;
///<summary> ///Storesthehandletothemousehookprocedure. ///</summary> privateinthMouseHook=0; ///<summary> ///Storesthehandletothekeyboardhookprocedure. ///</summary> privateinthKeyboardHook=0;
///<summary> ///DeclareMouseHookProcedureasHookProctype. ///</summary> privatestaticHookProcMouseHookProcedure; ///<summary> ///DeclareKeyboardHookProcedureasHookProctype. ///</summary> privatestaticHookProcKeyboardHookProcedure;
///<summary> ///Installsbothmouseandkeyboardhooksandstartsraisingevents ///</summary> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> publicvoidStart() { this.Start(true,true); }
///<summary> ///Installsbothoroneofmouseand/orkeyboardhooksandstartsraisingevents ///</summary> ///<paramname="InstallMouseHook"><b>true</b>ifmouseeventsmustbemonitored</param> ///<paramname="InstallKeyboardHook"><b>true</b>ifkeyboardeventsmustbemonitored</param> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> publicvoidStart(boolInstallMouseHook,boolInstallKeyboardHook) { //installMousehookonlyifitisnotinstalledandmustbeinstalled if(hMouseHook==0&&InstallMouseHook) { //CreateaninstanceofHookProc. MouseHookProcedure=newHookProc(MouseHookProc); //installhook hMouseHook=SetWindowsHookEx( WH_MOUSE_LL, MouseHookProcedure, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //IfSetWindowsHookExfails. if(hMouseHook==0) { //ReturnstheerrorcodereturnedbythelastunmanagedfunctioncalledusingplatforminvokethathastheDllImportAttribute.SetLastErrorflagset. interrorCode=Marshal.GetLastWin32Error(); //docleanup Stop(true,false,false); //InitializesandthrowsanewinstanceoftheWin32Exceptionclasswiththespecifiederror. thrownewWin32Exception(errorCode); } }
//installKeyboardhookonlyifitisnotinstalledandmustbeinstalled if(hKeyboardHook==0&&InstallKeyboardHook) { //CreateaninstanceofHookProc. KeyboardHookProcedure=newHookProc(KeyboardHookProc); //installhook hKeyboardHook=SetWindowsHookEx( WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE( Assembly.GetExecutingAssembly().GetModules()[0]), 0); //IfSetWindowsHookExfails. if(hKeyboardHook==0) { //ReturnstheerrorcodereturnedbythelastunmanagedfunctioncalledusingplatforminvokethathastheDllImportAttribute.SetLastErrorflagset. interrorCode=Marshal.GetLastWin32Error(); //docleanup Stop(false,true,false); //InitializesandthrowsanewinstanceoftheWin32Exceptionclasswiththespecifiederror. thrownewWin32Exception(errorCode); } } }
///<summary> ///Stopsmonitoringbothmouseandkeyboardeventsandrasingevents. ///</summary> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> publicvoidStop() { this.Stop(true,true,true); }
///<summary> ///Stopsmonitoringbothoroneofmouseand/orkeyboardeventsandrasingevents. ///</summary> ///<paramname="UninstallMouseHook"><b>true</b>ifmousehookmustbeuninstalled</param> ///<paramname="UninstallKeyboardHook"><b>true</b>ifkeyboardhookmustbeuninstalled</param> ///<paramname="ThrowExceptions"><b>true</b>ifexceptionswhichoccuredduringuninstallingmustbethrown</param> ///<exceptioncref="Win32Exception">Anywindowsproblem.</exception> publicvoidStop(boolUninstallMouseHook,boolUninstallKeyboardHook,boolThrowExceptions) { //ifmousehooksetandmustbeuninstalled if(hMouseHook!=0&&UninstallMouseHook) { //uninstallhook intretMouse=UnhookWindowsHookEx(hMouseHook); //resetinvalidhandle hMouseHook=0; //iffailedandexceptionmustbethrown if(retMouse==0&&ThrowExceptions) { //ReturnstheerrorcodereturnedbythelastunmanagedfunctioncalledusingplatforminvokethathastheDllImportAttribute.SetLastErrorflagset. interrorCode=Marshal.GetLastWin32Error(); //InitializesandthrowsanewinstanceoftheWin32Exceptionclasswiththespecifiederror. thrownewWin32Exception(errorCode); } }
//ifkeyboardhooksetandmustbeuninstalled if(hKeyboardHook!=0&&UninstallKeyboardHook) { //uninstallhook intretKeyboard=UnhookWindowsHookEx(hKeyboardHook); //resetinvalidhandle hKeyboardHook=0; //iffailedandexceptionmustbethrown if(retKeyboard==0&&ThrowExceptions) { //ReturnstheerrorcodereturnedbythelastunmanagedfunctioncalledusingplatforminvokethathastheDllImportAttribute.SetLastErrorflagset. interrorCode=Marshal.GetLastWin32Error(); //InitializesandthrowsanewinstanceoftheWin32Exceptionclasswiththespecifiederror. thrownewWin32Exception(errorCode); } } }
///<summary> ///Acallbackfunctionwhichwillbecalledeverytimeamouseactivitydetected. ///</summary> ///<paramname="nCode"> ///[in]Specifieswhetherthehookproceduremustprocessthemessage. ///IfnCodeisHC_ACTION,thehookproceduremustprocessthemessage. ///IfnCodeislessthanzero,thehookproceduremustpassthemessagetothe ///CallNextHookExfunctionwithoutfurtherprocessingandmustreturnthe ///valuereturnedbyCallNextHookEx. ///</param> ///<paramname="wParam"> ///[in]Specifieswhetherthemessagewassentbythecurrentthread. ///Ifthemessagewassentbythecurrentthread,itisnonzero;otherwise,itiszero. ///</param> ///<paramname="lParam"> ///[in]PointertoaCWPSTRUCTstructurethatcontainsdetailsaboutthemessage. ///</param> ///<returns> ///IfnCodeislessthanzero,thehookproceduremustreturnthevaluereturnedbyCallNextHookEx. ///IfnCodeisgreaterthanorequaltozero,itishighlyrecommendedthatyoucallCallNextHookEx ///andreturnthevalueitreturns;otherwise,otherapplicationsthathaveinstalledWH_CALLWNDPROC ///hookswillnotreceivehooknotificationsandmaybehaveincorrectlyasaresult.Ifthehook ///proceduredoesnotcallCallNextHookEx,thereturnvalueshouldbezero. ///</returns> privateintMouseHookProc(intnCode,intwParam,IntPtrlParam) { //ifokandsomeonelistenstoourevents if((nCode>=0)&&(OnMouseActivity!=null)) { //Marshallthedatafromcallback. MouseLLHookStructmouseHookStruct=(MouseLLHookStruct)Marshal.PtrToStructure(lParam,typeof(MouseLLHookStruct));
//detectbuttonclicked MouseButtonsbutton=MouseButtons.None; shortmouseDelta=0; switch(wParam) { caseWM_LBUTTONDOWN: //caseWM_LBUTTONUP: //caseWM_LBUTTONDBLCLK: button=MouseButtons.Left; break; caseWM_RBUTTONDOWN: //caseWM_RBUTTONUP: //caseWM_RBUTTONDBLCLK: button=MouseButtons.Right; break; caseWM_MOUSEWHEEL: //IfthemessageisWM_MOUSEWHEEL,thehigh-orderwordofmouseDatamemberisthewheeldelta. //OnewheelclickisdefinedasWHEEL_DELTA,whichis120. //(value>>16)&0xffff;retrievesthehigh-orderwordfromthegiven32-bitvalue &