class globalMouse
{
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void MouseEventHandle(MouseHookStruct Info);
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public IntPtr hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
const int WH_MOUSE = 14;
int hhook = 0;
public event MouseEventHandle MouseEvent;
public globalMouse()
{
hook();
}
~globalMouse()
{
unhook();
}
public void hook()
{
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_MOUSE, hookProc, hInstance, 0);
}
public void unhook()
{
UnhookWindowsHookEx(hhook);
}
/*
*
*
*
* problem - lParam.hwnd = 0.
* MyMouseHookStruct.hwnd = 0.
*
*/
public int hookProc(int code, IntPtr wParam, IntPtr lParam)
{
if (code >= 0)
{
if ((int)wParam == 0x204)
{
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
MouseEvent(MyMouseHookStruct);
}
}
return CallNextHookEx(hhook, code, wParam, lParam);
}
[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, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
}