How can I use ’Hooks’ in .NET

Platform: WinForms| Category: Win32

Please check out this article from the October 2000 issue of MSDN Magazine.

Allen Weng gives the following explanation in a post on the microsoft.public.dotnet.framework.windowsforms newgroup.

If what you are looking for is just to intercept and handle generic Windows messages such as WM_NCPAINT or alike, you can override WndProc (). You don’t need to use the hook procedure. Here is some code that does this:

public enum WinMsg 
{
	WM_KEYDOWN = 256,
	WM_KEYUP = 257,
	WM_PAINT = 15,
	WM_CREATE = 1
	.......
	.......
};

protected override void WndProc(ref System.Windows.Forms.Message m)
{
	.............. 
	if (m.Msg == (int) WinMsg.WM_PAINT)
	{
		m.Result = new IntPtr(0); // no further processing is needed.
		.......
		.......
	}
	..............
	base.WndProc(ref m);
}

But if you need to use a hook procedure, be cautious since they might interfere with normal execution of other applications. In some extreme cases, they might bring the whole system down if not processed correctly. Here is the code snippet that shows you how to do implement and use the hook procedure in .NET:

public class Win32Hook
{
	[DllImport('kernel32')]
	public static extern int GetCurrentThreadId();

	[DllImport( 'user32', CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)]
	public static extern int  SetWindowsHookEx( HookType idHook,
				HOOKPROC lpfn,
				int hmod,
				int dwThreadId
				);

	public enum HookType
	{
		WH_KEYBOARD = 2
	}
	public delegate int HOOKPROC(int nCode, int wParam, int lParam);

	private HOOKPROC hookProc; //private field with class scope

	public void SetHook()
	{
		 // set the keyboard hook
		hookProc = new HOOKPROC(this.MyKeyboardProc);

            		SetWindowsHookEx(HookType.WH_KEYBOARD, hookProc, 0,
GetCurrentThreadId());

	}

	public int MyKeyboardProc(int nCode, int wParam, int lParam)
	{
		return 0;
	}
}

To install the hook procedure

            Win32Hook hook = new Win32Hook();
            hook.SetHook();

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.