SetWindowsHookEx failing on beta2 x64
Sigh, I have some code from codeproject (http://www.codeproject.com/KB/cs/globalhook.aspx) for hooking global keyboard and mouse events. Suddenly now when I installed beta 2 of visual studio 2010 and .net framework 4.0 i breaks at thi开发者_Python百科s code:
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
Marshal.GetHINSTANCE(
Assembly.GetExecutingAssembly().GetModules()[0]),
0);
Oh, and I'm running on a X64 machine. Anyone know a way around this? Not an easy fix I know..
Just did this for my project recently. It works like a charm ) I'm almost sure it's about 2nd and 3rd arguments.
1 wrap KeyboardHookProcedure() like this:
//declate delegate type:
public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
//use a class member of this type and inject your callback into
m_hookproc = new HookProc(HookCallbackProcedure);
2 for 3rd argument:
IntPtr hInstance = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
3 be careful with Marshal.GetLastWin32Error() you have to use it strictly after the method you check for errors. ( see this fxcop rule)
the whole picture then looks like this:
IntPtr hInstance = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
IntPtr handle = SetWindowsHookEx( WH_KEYBOARD_LL, m_hookproc, hInstance, 0);
if (handle == IntPtr.Zero)
{
int error = Marshal.GetLastWin32Error();
//log the error or whatever
}
so that's all )
Leave the Instance parameter as 0. Seems XP requires it, but win7 doesnt.
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
0,
0);
精彩评论