问题描述
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Runtime.InteropServices;usingSystem.Reflection;usingSystem.Diagnostics;usingSystem.IO;usingSystem.Text.RegularExpressions;namespacetest{publicpartialclassForm1:Form{//委托publicstructCOPYDATASTRUCT{publicIntPtrdwData;publicintcbData;[MarshalAs(UnmanagedType.LPStr)]publicstringlpData;}publicdelegateintHookProc(intnCode,intwParam,IntPtrlParam);staticinthHook=0;publicconstintWH_KEYBOARD_LL=13;//LowLevel键盘截获,如果是WH_KEYBOARD=2,并不能对系统键盘截取,AcrobatReader会在你截取之前获得键盘。HookProcKeyBoardHookProcedure;//键盘Hook结构函数[StructLayout(LayoutKind.Sequential)]publicclassKeyBoardHookStruct{publicintvkCode;publicintscanCode;publicintflags;publicinttime;publicintdwExtraInfo;}#regionDllImport//设置钩子[DllImport("user32.dll")]publicstaticexternintSetWindowsHookEx(intidHook,HookProclpfn,IntPtrhInstance,intthreadId);//抽掉钩子[DllImport("user32.dll",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]publicstaticexternboolUnhookWindowsHookEx(intidHook);//调用下一个钩子[DllImport("user32.dll")]publicstaticexternintCallNextHookEx(intidHook,intnCode,intwParam,IntPtrlParam);[DllImport("kernel32.dll")]publicstaticexternintGetCurrentThreadId();[DllImport("kernel32.dll")]publicstaticexternIntPtrGetModuleHandle(stringname);#endregion#region自定义事件publicvoidHook_Start(){//安装键盘钩子if(hHook==0){KeyBoardHookProcedure=newHookProc(KeyBoardHookProc);//hHook=SetWindowsHookEx(2,//KeyBoardHookProcedure,//GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName),GetCurrentThreadId());hHook=SetWindowsHookEx(WH_KEYBOARD_LL,KeyBoardHookProcedure,GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName),0);//如果设置钩子失败.if(hHook==0){Hook_Clear();//thrownewException("设置Hook失败!");}}}//取消钩子事件publicvoidHook_Clear(){boolretKeyboard=true;if(hHook!=0){retKeyboard=UnhookWindowsHookEx(hHook);hHook=0;}//如果去掉钩子失败.if(!retKeyboard)thrownewException("UnhookWindowsHookExfailed.");}staticintnum=0;//这里可以添加自己想要的信息处理publicstaticintKeyBoardHookProc(intnCode,intwParam,IntPtrlParam){if(nCode>=0){KeyBoardHookStructkbh=(KeyBoardHookStruct)Marshal.PtrToStructure(lParam,typeof(KeyBoardHookStruct));if(kbh.vkCode!=0){num++;MessageBox.Show(kbh.vkCode+""+num);}return0;}returnCallNextHookEx(hHook,nCode,wParam,lParam);}#endregionpublicForm1(){InitializeComponent();}privatevoidbutton1_Click(objectsender,EventArgse){Hook_Start();}privatevoidbutton2_Click(objectsender,EventArgse){Hook_Clear();}}}vs调试时红色部分调用一次不调试时调用两次
解决方案
解决方案二:
按键消息,keydown,keyup都会触发的,你应该判断一下状态ifGetKeyState(wParam)<0thenGetKeyState原型SHORTGetKeyState(intnVirtKey);
解决方案三:
引用1楼bdmh的回复:
按键消息,keydown,keyup都会触发的,你应该判断一下状态ifGetKeyState(wParam)<0thenGetKeyState原型SHORTGetKeyState(intnVirtKey);http://blog.csdn.net/bdmh/article/details/6124127
那为什么调试时候显示一次啊