Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. runtime. interopservices;
Namespace windowsapplication3
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Public Delegate int hookproc (INT ncode, intptr wparam, intptr lparam );
// Define the hook handle
Static int hhook = 0;
// Define the hook type
Public const int wh_mouse = 7;
// Define the hook processing function
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;
}
// Import the Windows API function declaration. The functions used here are:
// Setwindowshookex, unhookwindowshookex, callnexthookex
[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 );
Private void button#click (Object sender, eventargs E)
{
If (hhook = 0)
{
Mousehookprocedure = new hookproc (form1.mousehookproc );
// Hook mounting
Hhook = setwindowshookex (wh_mouse,
Mousehookprocedure,
(Intptr) 0,
Appdomain. getcurrentthreadid ());
If (hhook = 0)
{
MessageBox. Show ("setwindowshookex failed ");
Return;
}
Button1.text = "unhook Windows Hook ";
}
Else
{
Bool ret = unhookwindowshookex (hhook );
If (ret = false)
{
MessageBox. Show ("unhookwindowshookex failed ");
Return;
}
Hhook = 0;
Button1.text = "set Windows Hook ";
This. Text = "Mouse hook ";
}
}
Public static int mousehookproc (INT ncode, intptr wparam, intptr lparam)
{
Mousehookstruct mymousehookstruct = (mousehookstruct) Marshal. ptrtostructure (lparam, typeof (mousehookstruct ));
If (ncode <0)
{
Return callnexthookex (hhook, ncode, wparam, lparam );
}
Else
{
String strcaption = "x =" +
Mymousehookstruct.pt. X. tostring ("D") +
"Y =" +
Mymousehookstruct.pt. Y. tostring ("D ");
Form tempform = form. activeform;
Tempform. Text = strcaption;
Return callnexthookex (hhook, ncode, wparam, lparam );
}
}
}
}