C#利用钩子控制鼠标
作者:清清月儿
主页:http://blog.csdn.net/21aspnet/ 时间:2007.5.11
工作中有这样的需求,某个控件panel的子控件textbox要实现只留鼠标右键copy,注意同时还不能影响其它panel的子控件textbox,怎么办?
答案是只有用钩子,在codeporject上找到这么一个钩子。
如图所示,第一个文本框只有copy功能。
UserActivityHook.cs
using
System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
namespace gma.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,
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
namespace gma.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,