SetWindowsHookEx not working when code placed in external dll - c#

HI i have a following code that reads mouse event
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
public enum MouseKeyType
{
MouseMoveOnly=512,
MouseLeftKeyDown=513,
MouseLeftKeyup=514,
MouseRightKeyDown = 516,
MouseRightKeyup = 517,
MouseMiddleKeyDown = 519,
MouseMiddleKeyup = 520,
MouseScroll=522
}
[StructLayout(LayoutKind.Sequential)]
public class MouseEventData
{
public Point point;
private int mouseData;
private int flags;
public int time;
//public int dwExtraInfo;
public bool IsScrollUp
{
get
{
return mouseData > -1;
}
}
public MouseKeyType mouseKeyType;
}
public class gc
{
// Event
public delegate void gcMouseEvents(object source, MouseEventData e);
public event gcMouseEvents gcevent;
// WIN32 hook
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx( int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
//just a delegate to simplify the type of
private delegate int HookProc(int nCode,int wParam, IntPtr lParam);
private HookProc _hookCallback;
public gc()
{
_hookCallback = new HookProc((x,y,z)=>
{
//string output = JsonConvert.SerializeObject(ptr);
//Console.WriteLine(output);
if (gcevent!=null)
{
MouseEventData ptr = (MouseEventData)Marshal.PtrToStructure(z, typeof(MouseEventData));
ptr.mouseKeyType = (MouseKeyType)y;
gcevent(this, ptr);
}
return 0;
});
SetWindowsHookEx(
14,
_hookCallback,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
0);
}
}
This seems to work fine in a form application when code placed in that project. BUt when code is placed in an console library and and a reference added then it dosent work..
I tried adding dlls to windows form etc and played with static etc but nothing seems to work when its
placed in a dll

Related

Global low-level mouse hook doesn't get called when UWP desktop app is out of focus

I'm creating a desktop UWP app and I need to set a global low level mouse hook to detect and change the position of it when it is moved to certain locations of the screen.
It works fine while my app's window is in focus and the values get logged correctly to the output window(meaning that the hook is working correctly).
This UWP app isn't going to be on the store and will only be used on a Windows 10 desktop (1903+).
I've tried calling SetWindowsHookEx on a different thread (which didn't do anything).
Tried also passing a thread ID when calling SetWindowsHookEx to no avail.
Also tried using the following restricted capabilities to prevent the app to suspend when not on focus: extendedExecutionUnconstrained and extendedBackgroundTaskTime along with the PreventFromSuspending method shown here.
Another thing I tried was to set uiAccess to true on the app manifest, which also didn't work.
The global hook is supposed to work even when the app isn't in the foreground, but instead it just works when it has the active window focus.
#region Structures
[StructLayout(LayoutKind.Sequential)]
/* MSLLHOOKSTRUCT */
public struct NativeMouseLowLevelHook
{
public override string ToString()
{
return $"{nameof(Point)}: {Point}, {nameof(MouseData)}: {MouseData}, {nameof(Flags)}: {Flags}";
}
public NativePoint Point;
public int MouseData;
public int Flags;
public int Time;
public UIntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public class NativePoint
{
public override string ToString()
{
return $"{nameof(X)}: {X}, {nameof(Y)}: {Y}";
}
public int X;
public int Y;
}
#endregion
#region Hook
public class ManagedMouseHook : SafeHandleZeroOrMinusOneIsInvalid
{
public static List<ManagedMouseHook> KnownHooks { get; set; } = new List<ManagedMouseHook>();
public HookProc HookImpl { get; set; }
public ManagedMouseHook() : base(true)
{
Hook();
}
private void Hook()
{
HookImpl = NativeHookCallback;
KnownHooks.Add(this);
using (var curProcess = Process.GetCurrentProcess())
using (var curModule = curProcess.MainModule)
{
DoHook(curModule);
}
}
private void DoHook(ProcessModule curModule)
{
SetHandle(SetWindowsHookEx(14 /*WH_MOUSE_LL*/, HookImpl, GetModuleHandle(curModule.ModuleName), 0));
}
private bool UnHook()
{
var result = UnhookWindowsHookEx(DangerousGetHandle());
KnownHooks.Remove(this);
HookImpl = null;
return result;
}
/* LowLevelMouseProc */
private IntPtr NativeHookCallback(int code, IntPtr wparam, IntPtr lparam)
{
if (code >= 0)
{
var info = (NativeMouseLowLevelHook) Marshal.PtrToStructure(lparam,
typeof(NativeMouseLowLevelHook));
Debug.WriteLine(info); //Output example: Point: X: 408, Y: 535, MouseData: 0, Flags: 0
return new IntPtr(-1);
}
return CallNextHookEx(IntPtr.Zero, code, wparam, lparam);
}
protected override bool ReleaseHandle()
{
return UnHook();
}
}
#endregion
#region Interop
public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetWindowsHookEx(int hookType, HookProc lpfn, IntPtr hMod, ulong dwThreadId);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam,
IntPtr lParam);
#endregion
Then, to start using it:
public ManagedMouseHook MouseHook { get; set; }
MouseHook/*property*/ = new ManagedMouseHook();
And to unhook:
MouseHook/*property*/.Close();
UWP apps are running in the sandbox, so that doesn't sound strange. If you think a bit it is a security problem if the app can receive such an input and as 'Security' is listed as No.1 characteristic of the UWP this behavior is expected.
I've decided with the help of the comments that the best way to do this is to use my UWP app as a front-end and using a win32 app for the hooking functionality itself.

An application created with C # has a thread hang

In Visual Studio C #, I'm creating an application that records mouse movements through hooking to track mouse movement.
This application works well under normal circumstances, but when the task manager or a particular game is running, the thread stops and the application does not work.
However, when I click the application window again, it tracks mouse movement again.
How do I get this application to work when I'm running Task Manager or a particular game?
class Hook
{
static private DateTime Set_time;
public static class GlobalMouseHook
{
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc Ipfn, IntPtr hlnstance, int threadld);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParm);
}
public static class MouseHook
{
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
public const int WH_MOUSE_LL = 14;
public static int hookHandle = 0;
private static GlobalMouseHook.HookProc callbackDelegate;
public static void StartHook(DateTime Set_time)
{
Hook.Set_time = Set_time;
callbackDelegate = new GlobalMouseHook.HookProc(CallBack);
if (hookHandle != 0)
{
return;
}
hookHandle = GlobalMouseHook.SetWindowsHookEx(WH_MOUSE_LL, callbackDelegate, IntPtr.Zero, 0);
}
public static void StopHook()
{
GlobalMouseHook.UnhookWindowsHookEx(hookHandle);
}
private enum MouseMessages
{
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_MOUSEMOVE = 0x0200,
WM_MOUSEWHEEL = 0x020A,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205
}
public static int CallBack(int nCode, IntPtr wParam, IntPtr lParam)
{
MouseHookStruct mouseInput = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
System.Diagnostics.Debug.WriteLine(mouseInput.pt.x + " : " + mouseInput.pt.y);
System.Diagnostics.Debug.WriteLine((MouseMessages)wParam);
System.Diagnostics.Debug.WriteLine(DateTime.Now-Set_time);
return GlobalMouseHook.CallNextHookEx(hookHandle, nCode, wParam, lParam);
}
}
}
I have attached additional code to use that hooking code.
public Form1 ()
{
Hook.MouseHook.StartHook (DateTime.Now);
InitializeComponent ();
}

SetWindowsHookEx does not work in C# .net core?

I'm using the following code trying to get OS wide keyboard inputs with no luck:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class InterceptKeys
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_hookID = SetHook(_proc);
while(true)
continue;
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine(vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
HookCallback is simply not being called. I have a suspicion it's trying to listen only to a form which doesn't exist rather than running system wide.
Low-level Windows hooks internally use Windows messaging. The thread that calls SetWindowsHookEx must have the message loop in the end, which allows to call HookCallback function. In C++ message loop looks like this:
MSG msg;
BOOL result;
for (;;)
{
result = GetMessage(&msg, nullptr, 0, 0);
if (result <= 0)
{
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Find all required PInvoke definitions for GetMessage, TranslateMessage, DispatchMessage and MSG, translate this code to C# and place it instead of your endless loop while(true). You can find all this stuff at PInvoke.Net, see also this Microsoft forum discussion:
Console keyboard hook not getting called
https://social.msdn.microsoft.com/Forums/vstudio/en-US/ed5be22c-cef8-4615-a625-d05caf113afc/console-keyboard-hook-not-getting-called?forum=csharpgeneral
I'm obviously very late but just hoping I could help (if the OP haven't have yet the help he/she needed) so I'm posting my answer.
It says in the MSDN documentation that when you want to set a system-wide hook, you must give the hMod parameter a
handle to the DLL containing the hook procedure pointed to by the lpfn
parameter
and
If the dwThreadId parameter is zero or specifies the identifier of a
thread created by a different process, the lpfn parameter must point
to a hook procedure in a DLL
but, look at this:
SetWindowsHookEx(2, kbdHookProc, GetModuleHandle("user32"), 0)
kbdHookProc is a function in my C# winforms application but the value I gave in the hMod parameter is the hinstance obtained by loading user32.dll via GetModuleHandle. I am using the keyboard hook (WH_KEYBOARD) to monitor locking of capslock, numlock and scroll lock keys. Don't ask me why I did that and would it work or why it works because I don't know but, yes, IT WORKS!
For a full answer to this;
As Alex says, you'll need a message loop to process windows messages and call your hooks,
public class MessageLoop
{
[DllImport("user32.dll")]
private static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin,
uint wMsgFilterMax);
[DllImport("user32.dll")]
private static extern bool TranslateMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
private static extern IntPtr DispatchMessage([In] ref MSG lpmsg);
[StructLayout(LayoutKind.Sequential)]
public struct MSG
{
IntPtr hwnd;
uint message;
UIntPtr wParam;
IntPtr lParam;
int time;
POINT pt;
int lPrivate;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
public static implicit operator System.Drawing.Point(POINT p)
{
return new System.Drawing.Point(p.X, p.Y);
}
public static implicit operator POINT(System.Drawing.Point p)
{
return new POINT(p.X, p.Y);
}
public override string ToString()
{
return $"X: {X}, Y: {Y}";
}
}
private Action InitialAction { get; }
private Thread? Thread { get; set; }
public bool IsRunning { get; private set; }
public MessageLoop(Action initialAction)
{
InitialAction = initialAction;
}
public void Start()
{
IsRunning = true;
Thread = new Thread(() =>
{
InitialAction.Invoke();
while (IsRunning)
{
var result = GetMessage(out var message, IntPtr.Zero, 0, 0);
if (result <= 0)
{
Stop();
continue;
}
TranslateMessage(ref message);
DispatchMessage(ref message);
}
});
Thread.Start();
}
public void Stop()
{
IsRunning = false;
}
}
I use a separate thread here to avoid blocking the main thread.
The InterceptKeys class as shown in the question needs no modification;
class InterceptKeys
{
// ...
public static void Main()
{
var loop = new MessageLoop(() => {
_hookID = SetHook(_proc);
});
while (Console.ReadKey(true) != ConsoleKey.X) // For exemplary purposes
{
continue;
}
loop.Stop();
}
// ...
}

Sending scroll commands with SendInput on Windows10 UWP applications

I have code very similar to this question running in a windows tray application, even with this exact code from the question I get the same behavior. It all works well on classic windows applications, such as Firefox, Chrome, Windows Explorer etc. However when the mouse focus gets to a UWP app such as Edge or Calendar or Mail the scroll becomes jittery and after a few dozen scrolls performed my application hangs and can't even be terminated from task manager (permission denied), this behavior is very reproducible.
I'll paste the code from the question here:
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace EnableMacScrolling
{
class InterceptMouse
{
const int INPUT_MOUSE = 0;
const int MOUSEEVENTF_WHEEL = 0x0800;
const int WH_MOUSE_LL = 14;
private static LowLevelMouseProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_hookID = SetHook(_proc);
if (_hookID == null)
{
MessageBox.Show("SetWindowsHookEx Failed");
return;
}
Application.Run();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelMouseProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_MOUSE_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && MouseMessages.WM_MOUSEWHEEL == (MouseMessages)wParam)
{
MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
Console.WriteLine(hookStruct.mouseData);
if (hookStruct.flags != -1) //prevents recursive call to self
{
INPUT input;
input = new INPUT();
input.type = INPUT_MOUSE;
input.mi.dx = 0;
input.mi.dy = 0;
input.mi.dwFlags = MOUSEEVENTF_WHEEL;
input.mi.time = 0;
input.mi.dwExtraInfo = 0;
input.mi.mouseData = -(hookStruct.mouseData >> 16);
try
{
SendInput(1, ref input, Marshal.SizeOf(input));
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
return (IntPtr)1;
}
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
private enum MouseMessages
{
WM_MOUSEWHEEL = 0x020A
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSLLHOOKSTRUCT
{
public POINT pt;
public int mouseData;
public int flags;
public int time;
public IntPtr dwExtraInfo;
}
public struct INPUT
{
public int type;
public MOUSEINPUT mi;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public uint dwFlags;
public int time;
public int dwExtraInfo;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("User32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT pInputs, int cbSize);
} }
Is it possible that I'm dealing with a bug in windows here? Any pointers to how I can find out what's going on?
Update:
I have created a test Win32 application in C++ to more easily reproduce/demonstrate the problem. The issue is with the SendCommand which when executed while any classic application is in focus works fine. However when executed while a UWP application is in focus, or even the windows launch/start menu causes the calling application (my application) to hang and be stuck until windows is restarted.
An effective workaround/solution for this problem is to perform the SendCommand call on another thread from the thread handling the hook callback. Immediately launching the thread that executes SendCommand and returning from the hook callback produces the desired behavior and doesn't cause any problems.
if (hookStruct.flags != -1) //prevents recursive call to self
That's rather important, yes. But how the statement could possibly do its job is very unclear. The expected value of this field is 0, 1 or 3. Never -1. You perhaps got mislead by another mouse hook that is active on your machine.
Now it does matter whether a WinRT app is in the foreground. Because then the message broker is involved and the field value changes, the LLMHF_LOWER_IL_INJECTED bit is turned on. WinRT apps run in a sandbox that run at a lower integrity level. So the field will not be -1 and your SendInput() call triggers the mouse hook again. On and on it goes, show is over when it runs out of stack.
So first possible fix is to use the field as intended, change the statement to:
if ((hookStruct.flags & 1) == 0)
Won't work if that presumed wonky mouse hook is corrupting the field, then consider using a static bool field in your class to break the recursion. Set it to true before the SendInput() call, false afterwards.
But I think I know why you are doing this, I too have been a victim of a trackpad that got it backwards. There is a much easier way to do it, just modify the FlipFlopWheel setting.

C# - No module handle?

I am trying to make a program that will be able to detect keyloggers on my system by installing a global hook on WH_DEBUG. My problem is, that GetModuleHandle (and - it seems - all of the other, more obscure ways of getting the module handle) return with null. I was hoping that someone here would be able to shed some light on the situation.
MainForm.cs:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace MouseTimer
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public static void log(String ltxt)
{
((MainForm)Application.OpenForms[0]).richTextBox1.Text += ltxt+"\n";
((MainForm)Application.OpenForms[0]).richTextBox1.SelectionStart = ((MainForm)Application.OpenForms[0]).richTextBox1.Text.Length;
((MainForm)Application.OpenForms[0]).richTextBox1.ScrollToCaret();
}
public int DbgEvt(int code, IntPtr wParam, IntPtr lParam)
{
log("DBGEVT: "+wParam.ToString());
return 0;
}
void MainFormLoad(object sender, EventArgs e)
{
WindowsHook wh = new WindowsHook(HookType.WH_DEBUG, DbgEvt);
wh.Install();
}
}
}
WindowsHook.cs:
public class WindowsHook
{
public delegate int HookProc(int code, IntPtr wParam, IntPtr lParam);
protected IntPtr m_hhook = IntPtr.Zero;
protected HookProc m_filterFunc = null;
protected HookType m_hookType;
public delegate void HookEventHandler(object sender, HookEventArgs e);
public event HookEventHandler HookInvoked;
protected void OnHookInvoked(HookEventArgs e)
{
if (HookInvoked != null)
HookInvoked(this, e);
}
public WindowsHook(HookType hook)
{
m_hookType = hook;
m_filterFunc = new HookProc(this.CoreHookProc);
}
public WindowsHook(HookType hook, HookProc func)
{
m_hookType = hook;
m_filterFunc = func;
}
protected int CoreHookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code < 0)
return CallNextHookEx(m_hhook, code, wParam, lParam);
HookEventArgs e = new HookEventArgs();
e.HookCode = code;
e.wParam = wParam;
e.lParam = lParam;
OnHookInvoked(e);
return CallNextHookEx(m_hhook, code, wParam, lParam);
}
public void Install()
{
using (Process p = Process.GetCurrentProcess())
using (ProcessModule m = p.MainModule)
{
m_hhook = SetWindowsHookEx(m_hookType, m_filterFunc,
GetModuleHandle(m.ModuleName), 0);
}
}
public void Uninstall()
{
UnhookWindowsHookEx(m_hhook);
m_hhook = IntPtr.Zero;
}
public bool IsInstalled
{
get{ return m_hhook != IntPtr.Zero; }
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
protected static extern IntPtr SetWindowsHookEx(HookType code,
HookProc func,
IntPtr hInstance,
int threadID);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
protected static extern int UnhookWindowsHookEx(IntPtr hhook);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
protected static extern int CallNextHookEx(IntPtr hhook,
int code, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
The thing is, when I try a (low-level) mouse hook, it hooks just fine without the module handle. So I'm not sure what the problem is. Can anyone help?
Thanks in advance,
Mike
Global hooks are not supported for .Net.
See here: http://support.microsoft.com/kb/318804?wa=wsignin1.0
From which I quote:
Except for the WH_KEYBOARD_LL low-level hook and the WH_MOUSE_LL
low-level hook, you cannot implement global hooks in the Microsoft
.NET Framework. To install a global hook, a hook must have a native
DLL export to inject itself in another process that requires a valid,
consistent function to call into. This behavior requires a DLL export.
The .NET Framework does not support DLL exports. Managed code has no
concept of a consistent value for a function pointer because these
function pointers are proxies that are built dynamically.

Categories

Resources