Ich versuch mich gerade in C# an globalen Maus- und Tastaturhooks. Der Tastatur-Hook funktioniert wie er soll, aber beim Maus-Hook habe ich ein Problem. Wenn man die Maus rumbewegt, nach dem man Hook aktiviert hat, gibt es plötzlich eine "CallbackOnCollectedDelegate-Exception".
Ich definiere ein Delegate, das ich dann der WinAPI-Funktion SetWindowsHookEx übergebe. Das Delegate wird auf Klassenebene deklariert, und im Konstruktor initialisiert. Trotzdem wird diese vom Garbage Collector eingesammelt und verursacht eine Exception, weil Windows die Funktion nicht mehr finden kann.
PHP Code:
class GlobalMouseHook {
[UnmanagedFunctionPointer(System.Runtime.InteropServices.CallingConvention.StdCall)]
public delegate int HookProc(int nCode, int wParam, MouseHookStruct lParam);
private HookProc _MouseHookProc;
public const int WH_MOUSE_LL = 14;
public GlobalMouseHook()
{
_MouseHookProc = new HookProc(MouseHookProc);
}
private int MouseHookProc(int nCode, int wParam, MouseHookStruct lParam)
{ ... }
public bool Hook()
{
hHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc,(IntPtr)0, 0);
if (hHook == 0)
{
return false;
}
return true;
}
public bool UnHook()
{
return UnhookWindowsHookEx(hHook);
}
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
IntPtr hInstance, int threadId);
[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,
int wParam, ref MouseHookStruct lParam);
}
PHP Code:
[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;
}
MfG,
noobyplay