Comme la question revient souvent, j'ai fait un exemple de hook pour la souris.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security;
public partial class MainForm : Form
{
#region Win32
[ StructLayout( LayoutKind.Sequential ) ]
private struct MSLLHOOKSTRUCT
{
public int X;
public int Y;
public int Data;
public int Flags;
public int Time;
public UIntPtr Extra;
}
[ DllImport( "user32.dll", SetLastError = true ), SuppressUnmanagedCodeSecurity ]
private static extern IntPtr SetWindowsHookEx( int hook, HookProc callback, IntPtr module, uint threadID );
[ DllImport( "user32.dll", SetLastError = true ), SuppressUnmanagedCodeSecurity ]
private static extern bool UnhookWindowsHookEx( IntPtr hHook );
[ DllImport( "user32.dll" ), SuppressUnmanagedCodeSecurity ]
private static extern IntPtr CallNextHookEx( IntPtr hHook, int code, UIntPtr wParam, IntPtr lParam );
private delegate IntPtr HookProc( int code, UIntPtr wParam, IntPtr lParam );
private const int WH_MOUSE_LL = 14;
private const int HC_ACTION = 0;
#endregion Win32
private IntPtr hHook = IntPtr.Zero;
private HookProc hookProc = null;
public MainForm( )
{
InitializeComponent( );
}
protected override void OnLoad( EventArgs e )
{
base.OnLoad( e );
hookProc = new HookProc( LowLevelMouseProc );
hHook = SetWindowsHookEx( WH_MOUSE_LL, hookProc, Marshal.GetHINSTANCE( this.GetType( ).Module ), 0 );
if ( hHook == IntPtr.Zero ) // Le hook ne s'installe pas en mode DEBUG.
MessageBox.Show( "Impossible d'installer le hook.", "Erreur" );
}
protected override void OnFormClosed( FormClosedEventArgs e )
{
base.OnFormClosed( e );
if ( hHook != IntPtr.Zero )
{
if ( !UnhookWindowsHookEx( hHook ) )
MessageBox.Show( "Impossible de désinstaller le hook.", "Erreur" );
hHook = IntPtr.Zero;
hookProc = null;
}
}
//
[ Lien ]
private IntPtr LowLevelMouseProc( int code, UIntPtr wParam, IntPtr lParam )
{
if ( code == HC_ACTION )
{
unsafe
{
MSLLHOOKSTRUCT* p = ( MSLLHOOKSTRUCT* )lParam;
Point screenPos = new Point( p->X, p->Y );
Point clientPos = this.PointToClient( screenPos );
this.Text = screenPos + " - " + clientPos; // Pour l'exemple.
}
}
return CallNextHookEx( hHook, code, wParam, lParam );
}
}