键盘钩子的邪门问题
写了个简单的键盘钩子可是出现很多不能理解的问题希望高手指教。
钩子函数:
LRESULT CALLBACK KeyHook(int nCode,
WPARAM wParam,
LPARAM lParam)
{
if (nCode> =HC_ACTION)
{
PKBDLLHOOKSTRUCT lParaStru = (PKBDLLHOOKSTRUCT)lParam;
switch(wParam)
{
case WM_KEYDOWN:
unsigned char* ucKey = new unsigned char[1];
ucKey[0]=lParaStru-> vkCode;
delete ucKey;
break;
case WM_KEYUP:
unsigned char* ucKey = new unsigned char[1];
ucKey[0]=lParaStru-> vkCode;
delete ucKey;
break;
}
}
}
从这里看并没有调用return(CallNextHookEx(hook,nCode,wParam,lParam));
应该不会放过任何键盘信息,可实际上只要有delete ucKey;就会把键盘事件传出去,后来把ucKey声明成 全局的可以解决此问题。
之后我又这样做把中间都替换成
ucKey[0]=lParaStru-> vkCode;
abc();
break;
abc函数:
bool abc(){
return false;
}
只要return false就不能拦截键盘事件,只要return true就可以拦截。很奇怪,有人知道是怎么回事么
[解决办法]
Return Value
If code is less than zero, the hook procedure must return the value returned by CallNextHookEx.
If code is greater than or equal to zero, and the hook procedure did not process the message, it is highly recommended that you call CallNextHookEx and return the value it returns; otherwise, other applications that have installed WH_KEYBOARD hooks will not receive hook notifications and may behave incorrectly as a result. If the hook procedure processed the message, it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.