C#如何捕捉windows鼠标事件?????????
C#如何捕捉windows鼠标事件?????????
------解决方案--------------------http://www.codeproject.com/csharp/globalsystemhook.asp
*****************************************************************************
欢迎使用CSDN论坛专用阅读器 : CSDN Reader(附全部源代码)
最新版本:20070212
http://www.cnblogs.com/feiyun0112/archive/2006/09/20/509783.html
------解决方案--------------------static int hMouseHook = 0;
HookProc MouseHookProcedure;
[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;
}
[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, Int32 wParam, IntPtr lParam);
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
public MouseHook()
{
Start();
}
~MouseHook()
{
Stop();
}
public void Start()
{
if(hMouseHook == 0)
{
MouseHookProcedure = new HookProc(MouseHookProc);
hMouseHook = SetWindowsHookEx( 14, MouseHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
if(hMouseHook == 0 )
{
Stop();
throw new Exception( "Error ");
}
}
}
public void Stop()
{
bool flag =true;
if(hMouseHook != 0)
{
flag = UnhookWindowsHookEx(hMouseHook);
hMouseHook = 0;
}
if (!flag) throw new Exception( "Error ");
}
private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
MouseHookStruct MyMouseHookStruct = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
// MyMouseHookStruct is result.
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}