Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

c# 4.0 - SetWindowsHookEx returns 0 when compiling for the .NET 4.0 framework in 32bit machines

I'm trying to set a low level windows keyboard hook to grab three keys pressed even if the application is not in focus. To do this I'm calling SetWindowsHookEx as

// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
    WH_KEYBOARD_LL,
    KeyboardHookProcedure,
    Marshal.GetHINSTANCE(
        Assembly.GetExecutingAssembly().GetModules()[0]),
    0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
    int errorCode = Marshal.GetLastWin32Error();
    //do cleanup
    Stop(false, true, false);
    //Initializes and throws a new instance of the Win32Exception class with the specified error. 
    throw new Win32Exception(errorCode);
}

This used to work on 32bit and 64bit machines using the .NET Framework 3.5 but after upgrading to the .NET Framework 4.0 stopped working on 32bit machines.

Does anyone know how to solve this so that I can use the 4.0 Framework and make this work on both 32bit and 64bit machines?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

import the dll like this:

[DllImport("kernel32.dll")]
    public static extern IntPtr GetModuleHandle(string name); 

then use

GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName)

to replace

Marshal.GetHINSTANCE(
    Assembly.GetExecutingAssembly().GetModules()[0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...