SetWindowsHookEx (user32)
Last changed: -93.41.3.12

.
Summary
Installs a hook to monitor certain types of events.

C# Signature:

[D)

    ' setup a keyboard hook
    SetWindowsHookEx(HookType.WH_KEYBOARD, Me.myCallbackDelegate, IntPtr.Zero, AppDomain.GetCurrentThreadId())
    End Sub

    <DllImport("user32.dll")> _
    Friend Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As HookProc, ByVal hInstance As IntPtr, ByVal threadId As Integer) As Integer
    End Function

    <DllImport("user32.dll")> _
    Friend Shared Function CallNextHookEx(ByVal hhk As intptr, ByVal nCode As Integer, ByVal wParam As intptr, ByVal lParam As intptr) As Integer
    End Function

    Private Function MyCallbackFunction(ByVal code As Integer, ByVal wParam As intptr, ByVal lParam As intptr) As Integer
    If (code < 0) Then
        'you need to call CallNextHookEx without further processing
        'and return the value returned by CallNextHookEx
        Return CallNextHookEx(IntPtr.Zero, code, wParam, lParam)    'unt
    End If
    ' we can convert the 2nd parameter (the key code) to a System.Windows.Forms.Keys enum constant
    Dim keyPressed As Keys = CType(wParam.ToInt32, Keys)
    Console.WriteLine(keyPressed)
    'return the value returned by CallNextHookEx
    Return CallNextHookEx(IntPtr.Zero, code, wParam, lParam)
    End Function
End Class

Alternative Managed API:

The ManagedWindowsApi project (http://mwinapi.sourceforge.net) provides a Hook class and subclasses for Journal hooks, Message hooks and Low-Level hooks.

Documentation

SetWindowsHookEx on MSDN

MSDN example of a mouse hook in C#: http://support.microsoft.com/default.aspx?scid=kb;en-us;318804#3

MSDN article on hooks in .NET: http://msdn.microsoft.com/msdnmag/issues/02/10/CuttingEdge/

MSDN article on KeyboardProc: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/keyboardproc.asp

Stephen Toub entry on low-level keyboard hook in C#: http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx

Stephen Toub entry on low-level mouse hook on C#: http://blogs.msdn.com/toub/archive/2006/05/03/589468.aspx

.