WINCE6.0 键盘钩子 SetWindowsHookEx返回0,安装钩子失败,求解

周美文 2014-01-10 05:18:18
背景是参照网上用 C#写了个键盘钩子类,然后到wince6.0系统下运行程序发现 键盘钩子安装失败,有哪位对这方面有所了解的啊,还请帮忙分析分析!代码如下,其中
hHookKey = SetWindowsHookEx(WH_KEYBOARD_LL, hookKeyDeleg, GetModuleHandle(null), 0);为0

public class HookKeyClass
{
public delegate int HookKeyProc(int code, IntPtr wParam, IntPtr lParam);
public delegate void KeyEventHandler(int KeyValue);
public event KeyEventHandler KeyEvent;
private HookKeyProc hookKeyDeleg;
private int hHookKey = 0;
public HookKeyClass()
{
Start();
}

~HookKeyClass()
{
Stop();
}


#region public methods
//安装钩子
private void Start()
{
if (hHookKey != 0)
{
//Unhook the previouse one
this.Stop();
}

hookKeyDeleg = new HookKeyProc(HookKeyProcedure);
hHookKey = SetWindowsHookEx(WH_KEYBOARD_LL, hookKeyDeleg, GetModuleHandle(null), 0);
if (hHookKey == 0)
{
throw new SystemException("Failed acquiring of the hook.");
}
}

//拆除钩子
private void Stop()
{
UnhookWindowsHookEx(hHookKey);
}

#endregion


#region protected and private methods
private int HookKeyProcedure(int code, IntPtr wParam, IntPtr lParam)
{
switch ((int)wParam)
{
case 257: //按下响应
KBDLLHOOKSTRUCT hookStruct = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(KBDLLHOOKSTRUCT));
if (code < 0)
{
return CallNextHookEx(hookKeyDeleg, code, wParam, lParam);
}
//if(hookStruct.vkCode==201 |
KeyEvent(hookStruct.vkCode);
break;
case 256:

break;

default: break;
}

return CallNextHookEx(hookKeyDeleg, code, wParam, lParam);
}
#endregion


#region P/Invoke declarations

[DllImport("coredll.dll")]
private static extern int SetWindowsHookEx(int type, HookKeyProc HookKeyProc, IntPtr hInstance, int m);
//private static extern int SetWindowsHookEx(int type, HookMouseProc HookMouseProc, IntPtr hInstance, int m);

[DllImport("coredll.dll")]
private static extern IntPtr GetModuleHandle(string mod);


[DllImport("coredll.dll")]
private static extern int CallNextHookEx(HookKeyProc hhk, int nCode, IntPtr wParam, IntPtr lParam);


[DllImport("coredll.dll")]
private static extern int GetCurrentThreadId();

[DllImport("coredll.dll", SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
private struct KBDLLHOOKSTRUCT
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public IntPtr dwExtraInfo;
}

const int WH_KEYBOARD_LL = 20;
public class KeyBoardInfo
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
}
#endregion
}
...全文
93 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cheery_an 2014-01-10
  • 打赏
  • 举报
回复
先网上查下吧,比如:http://www.csharpwin.com/csharpspace/3766r5747.shtml
周美文 2014-01-10
  • 打赏
  • 举报
回复
以前也没接触过wince系统、钩子什么的,着实有些不知从哪下手

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧