I have found similar questions on this page, but I can't seem to figure out how to interpret the answers or figure out if they are truly duplicates.
Here are the possible duplicates I've found, with comments:
SetWindowsHookEx returns 0 when compiling for the .NET 4.0 framework in 32bit machines
It doesn't seem to return 0 on mine, but I noticed that the handle reported when it crashes (.NET 4.0 on 32-bit) is way different from the handle reported when it runs (.NET 3.5 on 32-bit), like crash handle = 523727, and working handle = 172738378.
Calling SetWindowsHookEx inside VS2008 debugger always returns NULL
I can repro my problem when running outside of Visual Studio
-
This seems most promising, except that the comments to the deleted answer mentions I should use LoadLibrary and GetProcAddress to load user32.dll in .NET 4.0 since something about loading assemblies changed. I'm pretty sure, however, that it is my own module it can't find, but I don't know if this applies.
The comments in question on the deleted answer to that last one, by Hans Passant, reads:
Are you using .NET 4.0? Its CLR changed the way assemblies are loaded, there is no longer a LoadLibrary call, there won't be module handle for them. Using GetEntryAssembly() instead would be another fix. – Hans Passant May 5 at 19:43
So, what's the word here? Are you using .NET 4.0? Did you try using LoadLibrary("user32.dll") to get a usable DLL handle? – Hans Passant May 6 at 15:43
I'm pretty sure I don't need to do this, but obviously I'm not 100% sure. The question I'm left with if I need to change this, is why it works on 64-bit OS, when compiled for Any CPU
, but doesn't work on 32-bit, in any configuration.
If indeed something has changed regarding loading of .NET assemblies, so that I don't get a proper handle for the class library, I have the following questions:
- Is there any way I can trick this into doing what I want, without having to downgrade to .NET 3.5 or change the hook library to unmanaged?
- Why does it work when running on 64-bit OS, but not on 32-bit?
Background
I have built a program, in .NET 4.0, that uses SetWindowsHookEx with the WH_KEYBOARD_LL hook type to capture key presses. This runs nicely on my 64-bit Windows 7, but crashes with a "module not found" when the keyboard hook is installed on 32-bit Windows 7.
Here's what I've tried:
- Compile for x86, run on 64-bit OS, crashes with "module not found"
- Compile for x86, run on 32-bit OS, crashes
- Compile for Any CPU, run on 64-bit OS, runs nicely
- Compile for Any CPU, run on 32-bit OS, crashes
- Switch to .NET 3.5 and repeat the above four cases, they all work
I'd rather not switch my code to .NET 3.5, since I'm using a few of my class libraries to ease the work, and the latest code is only in .NET 4.0.
You can download a .ZIP-file with everything as a Visual Studio 2010 project if you want, or you can paste in the following two files.
To recreate if you want to go down that route:
- Create a new console-project, .NET 4.0
- Add another class-library project, also .NET 4.0
- Add a reference to the class-library project from the console-program project
- Paste in the Program.cs content below into the Program.cs file you have in the console project
- Paste in the Hook.cs content below into a file in the class-library project. You can paste it into the Class1.cs default file, or add another file. You can not put this into the console project
Then build and run, test various configurations.
Program.cs
using System;
using HookLib;
namespace HookTest
{
class Program
{
static void Main()
{
var hook = new Hook();
Console.Out.WriteLine("hooking");
hook.Enable();
Console.Out.WriteLine("hooked");
Console.Out.WriteLine("unhooking");
hook.Disable();
Console.Out.WriteLine("unhooked");
}
}
}
Hook.cs
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
namespace HookLib
{
public class Hook
{
private IntPtr _Handle;
private HookProcDelegate _Hook;
public void Enable()
{
Module module = Assembly.GetExecutingAssembly().GetModules()[0];
if (module != null)
Console.Out.WriteLine("found module");
IntPtr moduleHandle = Marshal.GetHINSTANCE(module);
if (moduleHandle != IntPtr.Zero)
Console.Out.WriteLine("got module handle: " +
moduleHandle.ToString());
_Hook = HookProc;
_Handle = SetWindowsHookEx(WH_KEYBOARD_LL, _Hook, moduleHandle, 0);
if (_Handle == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
public void Disable()
{
bool ok = UnhookWindowsHookEx(_Handle);
_Handle = IntPtr.Zero;
if (!ok)
throw new Win32Exception(Marshal.GetLastWin32Error());
}
private delegate int HookProcDelegate(
int code, IntPtr wParam, IntPtr lParam);
private int HookProc(int code, IntPtr wParam, IntPtr lParam)
{
return CallNextHookEx(_Handle, code, wParam, lParam);
}
private const int WH_KEYBOARD_LL = 13;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(
int hookType, HookProcDelegate lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", SetLastError = true)]
private static extern int CallNextHookEx(
IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
}
}