`
tiandirensoon
  • 浏览: 596483 次
文章分类
社区版块
存档分类
最新评论

C#利用钩子控制鼠标【月儿原创】

 
阅读更多

C#利用钩子控制鼠标

作者:清清月儿

主页:http://blog.csdn.net/21aspnet/ 时间:2007.5.11

工作中有这样的需求,某个控件panel的子控件textbox要实现只留鼠标右键copy,注意同时还不能影响其它panel的子控件textbox,怎么办?
答案是只有用钩子,在codeporject上找到这么一个钩子。

如图所示,第一个文本框只有copy功能。


UserActivityHook.cs


usingSystem;
usingSystem.Runtime.InteropServices;
usingSystem.Reflection;
usingSystem.Threading;
usingSystem.Windows.Forms;
usingSystem.ComponentModel;

namespacegma.System.Windows
...{
/**////<summary>
///Thisclassallowsyoutotapkeyboardandmouseand/ortodetecttheiractivityevenwhenan
///applicationrunesinbackgroundordoesnothaveanyuserinterfaceatall.Thisclassraises
///common.NETeventswithKeyEventArgsandMouseEventArgssoyoucaneasilyretrieveanyinformationyouneed.
///</summary>

publicclassUserActivityHook
...{
Windowsstructuredefinitions#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


Windowsfunctionimports#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


Windowsconstants#regionWindowsconstants

//valuesfromWinuser.hinMicrosoftSDK.
/**////<summary>
///WindowsNT/2000/XP:Installsahookprocedurethatmonitorslow-levelmouseinputevents.
///</summary>

privateconstintWH_MOUSE_LL=14;
/**////<summary>
///WindowsNT/2000/XP:Installsahookprocedurethatmonitorslow-levelkeyboardinputevents.
///</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
mouseDelta=(short)((mouseHookStruct.mouseData>>16)&0xffff);
//TODO:XBUTTONS(Ihaventthemsowasunabletotest)
//IfthemessageisWM_XBUTTONDOWN,WM_XBUTTONUP,WM_XBUTTONDBLCLK,WM_NCXBUTTONDOWN,WM_NCXBUTTONUP,
//orWM_NCXBUTTONDBLCLK,thehigh-orderwordspecifieswhichXbuttonwaspressedorreleased,
//andthelow-orderwordisreserved.Thisvaluecanbeoneormoreofthefollowingvalues.
//Otherwise,mouseDataisnotused.
break;
}


//doubleclicks
intclickCount=0;
if(button!=MouseButtons.None)
if(wParam==WM_LBUTTONDBLCLK||wParam==WM_RBUTTONDBLCLK)clickCount=2;
elseclickCount=1;

//generateevent
MouseEventArgse=newMouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
//raiseit
OnMouseActivity(this,e);
}

//callnexthook
returnCallNextHookEx(hMouseHook,nCode,wParam,lParam);
}


/**////<summary>
///Acallbackfunctionwhichwillbecalledeverytimeakeyboardactivitydetected.
///</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>

privateintKeyboardHookProc(intnCode,Int32wParam,IntPtrlParam)
...{
//indicatesifanyofunderlaingeventssete.Handledflag
boolhandled=false;
//itwasokandsomeonelistenstoevents
if((nCode>=0)&&(KeyDown!=null||KeyUp!=null||KeyPress!=null))
...{
//readstructureKeyboardHookStructatlParam
KeyboardHookStructMyKeyboardHookStruct=(KeyboardHookStruct)Marshal.PtrToStructure(lParam,typeof(KeyboardHookStruct));
//raiseKeyDown
if(KeyDown!=null&&(wParam==WM_KEYDOWN||wParam==WM_SYSKEYDOWN))
...{
KeyskeyData
=(Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgse
=newKeyEventArgs(keyData);
KeyDown(
this,e);
handled
=handled||e.Handled;
}


//raiseKeyPress
if(KeyPress!=null&&wParam==WM_KEYDOWN)
...{
boolisDownShift=((GetKeyState(VK_SHIFT)&0x80)==0x80?true:false);
boolisDownCapslock=(GetKeyState(VK_CAPITAL)!=0?true:false);

byte[]keyState=newbyte[256];
GetKeyboardState(keyState);
byte[]inBuffer=newbyte[2];
if(ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags)
==1)
...{
charkey=(char)inBuffer[0];
if((isDownCapslock^isDownShift)&&Char.IsLetter(key))key=Char.ToUpper(key);
KeyPressEventArgse
=newKeyPressEventArgs(key);
KeyPress(
this,e);
handled
=handled||e.Handled;
}

}


//raiseKeyUp
if(KeyUp!=null&&(wParam==WM_KEYUP||wParam==WM_SYSKEYUP))
...{
KeyskeyData
=(Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgse
=newKeyEventArgs(keyData);
KeyUp(
this,e);
handled
=handled||e.Handled;
}


}


//ifeventhandledinapplicationdonothandofftootherlisteners
if(handled)
return1;
else
returnCallNextHookEx(hKeyboardHook,nCode,wParam,lParam);
}

}

}


Form1.cs

usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;

namespaceWindowsApplication2
...{
/**////<summary>
///Form1的摘要说明。清清月儿主页:http://blog.csdn.net/21aspnet/
///</summary>

publicclassForm1:System.Windows.Forms.Form
...{
privateSystem.Windows.Forms.TextBoxtextBox1;
privateSystem.Windows.Forms.TextBoxtextBox2;
privateSystem.Windows.Forms.Panelpanel1;
/**////<summary>
///必需的设计器变量。
///</summary>

privateSystem.ComponentModel.Containercomponents=null;

publicForm1()
...{
//
//Windows窗体设计器支持所必需的
//
InitializeComponent();

//
//TODO:在InitializeComponent调用后添加任何构造函数代码
//
}


/**////<summary>
///清理所有正在使用的资源。
///</summary>

protectedoverridevoidDispose(booldisposing)
...{
if(disposing)
...{
if(components!=null)
...{
components.Dispose();
}

}

base.Dispose(disposing);
}


Windows窗体设计器生成的代码#regionWindows窗体设计器生成的代码
/**////<summary>
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///</summary>

privatevoidInitializeComponent()
...{
this.textBox1=newSystem.Windows.Forms.TextBox();
this.textBox2=newSystem.Windows.Forms.TextBox();
this.panel1=newSystem.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
//textBox1
//
this.textBox1.Location=newSystem.Drawing.Point(0,8);
this.textBox1.Name="textBox1";
this.textBox1.Size=newSystem.Drawing.Size(256,20);
this.textBox1.TabIndex=1;
this.textBox1.Text="111";
//
//textBox2
//
this.textBox2.Location=newSystem.Drawing.Point(8,48);
this.textBox2.Multiline=true;
this.textBox2.Name="textBox2";
this.textBox2.Size=newSystem.Drawing.Size(256,176);
this.textBox2.TabIndex=2;
this.textBox2.Text="textBox2";
//
//panel1
//
this.panel1.Controls.Add(this.textBox1);
this.panel1.Location=newSystem.Drawing.Point(8,0);
this.panel1.Name="panel1";
this.panel1.Size=newSystem.Drawing.Size(280,40);
this.panel1.TabIndex=3;
//
//Form1
//
this.AutoScaleBaseSize=newSystem.Drawing.Size(5,13);
this.ClientSize=newSystem.Drawing.Size(272,229);
this.Controls.Add(this.panel1);
this.Controls.Add(this.textBox2);
this.Name="Form1";
this.Text="Form1";
this.Load+=newSystem.EventHandler(this.Form1_Load);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);

}

#endregion


/**////<summary>
///应用程序的主入口点。
///</summary>

[STAThread]
staticvoidMain()
...{
Application.Run(
newForm1());

}



publicvoidMyKeyDown(objectsender,KeyEventArgse)
...{
}


publicvoidMyKeyPress(objectsender,KeyPressEventArgse)
...{
}


publicvoidMyKeyUp(objectsender,KeyEventArgse)
...{
}



voidchoose_OnMouseActivity(objectsender,MouseEventArgse)
...{
//自定义右键
//if(ActiveControl.Parent==panel1)备用
//if(ActiveControl.ParentisSystem.Windows.Forms.Panel)备用
if(ActiveControl==textBox1)
...{
MenuItemcopy
=newMenuItem("copy");
copy.Click
+=newEventHandler(copy_Click);
MenuItem[]menuItems
=newMenuItem[]...{copy};

ContextMenubuttonMenu
=newContextMenu(menuItems);
textBox1.ContextMenu
=buttonMenu;
//this.ActiveControl.ContextMenu=buttonMenu;备用
}

}


privatevoidcopy_Click(objectsender,EventArgse)
...{

Clipboard.SetDataObject(textBox1.SelectedText);
//复制到剪切板

}


privatevoidForm1_Load(objectsender,System.EventArgse)
...{
//初始化
gma.System.Windows.UserActivityHookchoosesc=newgma.System.Windows.UserActivityHook();
choosesc.OnMouseActivity
+=newMouseEventHandler(choose_OnMouseActivity);
//choosesc.KeyDown+=newKeyEventHandler(MyKeyDown);
//choosesc.KeyPress+=newKeyPressEventHandler(MyKeyPress);
//choosesc.KeyUp+=newKeyEventHandler(MyKeyUp);

}


}

}


说明:这个钩子有点问题,就是一次只能打开一个窗口(如果该窗口使用钩子),打开后一定要关闭否则出问题,后果很严重!!!

经典钩子:

之一:http://www.codeproject.com/csharp/globalhook.asp

之二:http://www.codeproject.com/csharp/GlobalSystemHook.asp

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics