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

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,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值