[APORTE] Ejemplo de un LL-Hook para el Mouse.

Iniciado por Eleкtro, 28 Junio 2014, 08:14 AM

0 Miembros y 1 Visitante están viendo este tema.

Eleкtro

Hola

Para todos los que estén interesados en iniciarse en los Hooks de bajo nivel (en lo cual yo no soy ningún experto) esto les podría servir, ya que considero haberlo dejado muy bien documentado y se puede aprender algo solo leyendo los comentarios XML.

Simplemente es un Hook que intercepta los eventos del ratón, pudiendo suscribirse a ellos, nada más que eso.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 05-13-2014
' ***********************************************************************
' <copyright file="MouseHook.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Instructions "

' Go to page:
' Project > Properties > Debug
'
' And uncheck the option:
' Enable the Visual Studio Hosting Process

#End Region

#Region " Usage Examples "

' ''' <summary>
' ''' A low level mouse hook that captures mouse events.
' ''' </summary>
'Private WithEvents MouseEvents As MouseHook = Nothing

' ''' <summary>
' ''' Handles the 'MouseLeftDown' event of the Mouse Hook.
' ''' </summary>
' ''' <param name="MouseLocation">Indicates the mouse [X,Y] coordinates.</param>
'Private Sub MouseEvents_MouseLeftDown(ByVal MouseLocation As Point) Handles MouseEvents.MouseLeftDown
'
'    Debug.WriteLine(String.Format("Mouse Left Down At: x={0}, y={1}", CStr(MouseLocation.X), CStr(MouseLocation.Y)))
'
'End Sub

' ''' <summary>
' ''' Handles the 'MouseLeftUp' event of the Mouse Hook.
' ''' </summary>
' ''' <param name="MouseLocation">Indicates the mouse [X,Y] coordinates.</param>
'Private Sub MouseEvents_MouseLeftUp(ByVal MouseLocation As Point) Handles MouseEvents.MouseLeftUp
'
'    Debug.WriteLine(String.Format("Mouse Left Up At: x={0}, y={1}", CStr(MouseLocation.X), CStr(MouseLocation.Y)))
'
'End Sub

' ''' <summary>
' ''' Handles the 'MouseMove' event of the Mouse Hook.
' ''' </summary>
' ''' <param name="MouseLocation">Indicates the mouse [X,Y] coordinates.</param>
'Private Sub MouseEvents_MouseMove(ByVal MouseLocation As Point) Handles MouseEvents.MouseMove
'
'    Debug.WriteLine(String.Format("Mouse Moved To: x={0}, y={1}", CStr(MouseLocation.X), CStr(MouseLocation.Y)))
'
'End Sub

' ''' <summary>
' ''' Handles the 'Click' event of the 'ButtonStartHook' control.
' ''' </summary>
'Private Sub ButtonStartHook() Handles ButtonStartHook.Click

'    ' Start the Mouse Hook.
'    MouseEvents = New MouseHook

'End Sub

' ''' <summary>
' ''' Handles the 'Click' event of the 'ButtonStopHook' control.
' ''' </summary>
'Private Sub ButtonStopHook() Handles ButtonStopHook.Click

'    ' Stop the Mouse Hook.
'    MouseEvents = Nothing

'End Sub

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.InteropServices

#End Region

#Region " MouseHook "

''' <summary>
''' A low level mouse hook class that captures mouse events.
''' </summary>
Public Class MouseHook

#Region " WinAPI "

#Region " Methods "

   ''' <summary>
   ''' Passes the hook information to the next hook procedure in the current hook chain.
   ''' A hook procedure can call this function either before or after processing the hook information.
   ''' For more info see here:
   ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="idHook">
   ''' This parameter is ignored.
   ''' </param>
   ''' <param name="nCode">
   ''' The hook code passed to the current hook procedure.
   ''' The next hook procedure uses this code to determine how to process the hook information.
   ''' </param>
   ''' <param name="wParam">
   ''' The wParam value passed to the current hook procedure.
   ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
   ''' </param>
   ''' <param name="lParam">
   ''' The lParam value passed to the current hook procedure.
   ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
   ''' </param>
   ''' <returns>
   ''' This value is returned by the next hook procedure in the chain.
   ''' The current hook procedure must also return this value.
   ''' The meaning of the return value depends on the hook type.
   ''' For more information, see the descriptions of the individual hook procedures.
   ''' </returns>
   <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
   Private Shared Function CallNextHookEx(
          ByVal idHook As Integer,
          ByVal nCode As Integer,
          ByVal wParam As Integer,
          ByVal lParam As MSLLHOOKSTRUCT
   ) As Integer
   End Function

   ''' <summary>
   ''' Installs an application-defined hook procedure into a hook chain.
   ''' You would install a hook procedure to monitor the system for certain types of events.
   ''' These events are associated either with a specific thread
   ''' or with all threads in the same desktop as the calling thread.
   ''' For more info see here:
   ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="idHook">
   ''' The type of hook procedure to be installed.
   ''' </param>
   ''' <param name="lpfn">
   ''' A pointer to the hook procedure.
   ''' If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process,
   ''' the lpfn parameter must point to a hook procedure in a DLL.
   ''' Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
   ''' </param>
   ''' <param name="hInstance">
   ''' A handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
   ''' The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
   ''' the current process and if the hook procedure is within the code associated with the current process.
   ''' </param>
   ''' <param name="threadId">
   ''' The identifier of the thread with which the hook procedure is to be associated.
   ''' For desktop apps, if this parameter is zero, the hook procedure is associated
   ''' with all existing threads running in the same desktop as the calling thread.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is the handle to the hook procedure.
   ''' If the function fails, the return value is NULL.
   ''' </returns>
   <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
   Private Shared Function SetWindowsHookEx(
          ByVal idHook As HookType,
          ByVal lpfn As MouseProcDelegate,
          ByVal hInstance As IntPtr,
          ByVal threadId As Integer
   ) As Integer
   End Function

   ''' <summary>
   ''' Removes a hook procedure installed in a hook chain by the 'SetWindowsHookEx' function.
   ''' For more info see here:
   ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644993%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="idHook">
   ''' A handle to the hook to be removed.
   ''' This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
   ''' </param>
   ''' <returns>
   ''' If the function succeeds, the return value is nonzero.
   ''' If the function fails, the return value is zero.
   ''' </returns>
   <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
   Private Shared Function UnhookWindowsHookEx(
          ByVal idHook As Integer
   ) As Boolean
   End Function

#End Region

#Region " Enums "

   ''' <summary>
   ''' Indicates a type of Hook procedure to be installed.
   ''' </summary>
   <Description("Enum used in 'idHook' parameter of 'SetWindowsHookEx' function")>
   Private Enum HookType As Integer

       ' **************************************
       ' This enumeration is partially defined.
       ' **************************************

       ''' <summary>
       ''' Installs a hook procedure that monitors low-level mouse input events.
       ''' For more information, see the LowLevelMouseProc hook procedure.
       ''' </summary>
       WH_MOUSE_LL = 14

   End Enum

#End Region

#Region " Structures "

   ''' <summary>
   ''' Contains information about a low-level mouse input event.
   ''' </summary>
   <Description("Structure used in 'lParam' parameter of 'CallNextHookEx' function")>
   Private Structure MSLLHOOKSTRUCT

       ''' <summary>
       ''' The ptThe x- and y-coordinates of the cursor, in screen coordinates.
       ''' </summary>
       Public pt As Point

       ''' <summary>
       ''' If the message is 'WM_MOUSEWHEEL', the high-order word of this member is the wheel delta.
       ''' The low-order word is reserved.
       ''' A positive value indicates that the wheel was rotated forward, away from the user;
       ''' a negative value indicates that the wheel was rotated backward, toward the user.
       ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
       ''' </summary>
       Public mouseData As Integer

       ''' <summary>
       ''' The event-injected flag.
       ''' </summary>
       Public flags As Integer

       ''' <summary>
       ''' The time stamp for this message.
       ''' </summary>
       Public time As Integer

       ''' <summary>
       ''' Additional information associated with the message.
       ''' </summary>
       Public dwExtraInfo As Integer

   End Structure

#End Region

#End Region

#Region " Variables "

   ''' <summary>
   '''
   ''' </summary>
   Private MouseHook As Integer

#End Region

#Region " Delegates "

   ''' <summary>
   ''' Delegate MouseProcDelegate
   ''' </summary>
   ''' <returns>System.Int32.</returns>
   Private Delegate Function MouseProcDelegate(
           ByVal nCode As Integer,
           ByVal wParam As Integer,
           ByRef lParam As MSLLHOOKSTRUCT
   ) As Integer

   ''' <summary>
   ''' </summary>
   Private MouseHookDelegate As MouseProcDelegate

#End Region

#Region " Enums "

   ''' <summary>
   ''' Indicates a Windows Message related to a mouse events.
   ''' For more info see here:
   ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ff468877%28v=vs.85%29.aspx
   ''' </summary>
   Private Enum MouseWindowsMessages As Integer

       ''' <summary>
       ''' Posted to a window when the cursor moves.
       ''' If the mouse is not captured, the message is posted to the window that contains the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MOUSEMOVE = &H200

       ''' <summary>
       ''' Posted when the user presses the left mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_LBUTTONDOWN = &H201

       ''' <summary>
       ''' Posted when the user releases the left mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_LBUTTONUP = &H202

       ''' <summary>
       ''' Posted when the user double-clicks the left mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_LBUTTONDBLCLK = &H203

       ''' <summary>
       ''' Posted when the user presses the right mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_RBUTTONDOWN = &H204

       ''' <summary>
       ''' Posted when the user releases the right mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_RBUTTONUP = &H205

       ''' <summary>
       ''' Posted when the user double-clicks the right mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_RBUTTONDBLCLK = &H206

       ''' <summary>
       ''' Posted when the user presses the middle mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MBUTTONDOWN = &H207

       ''' <summary>
       ''' Posted when the user releases the middle mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MBUTTONUP = &H208

       ''' <summary>
       ''' Posted when the user double-clicks the middle mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MBUTTONDBLCLK = &H209

       ''' <summary>
       ''' Sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated.
       ''' The DefWindowProc function propagates the message to the window's parent.
       ''' There should be no internal forwarding of the message,
       ''' since DefWindowProc propagates it up the parent chain until it finds a window that processes it.
       ''' </summary>
       WM_MOUSEWHEEL = &H20A

   End Enum

   ''' <summary>
   ''' Indicates the whell direction of the mouse.
   ''' </summary>
   Public Enum WheelDirection

       ''' <summary>
       ''' The wheel is moved up.
       ''' </summary>
       WheelUp

       ''' <summary>
       ''' The wheel is moved down.
       ''' </summary>
       WheelDown

   End Enum

#End Region

#Region " Events "

   ''' <summary>
   ''' Occurs when the mouse moves.
   ''' </summary>
   Public Event MouseMove(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button is pressed.
   ''' </summary>
   Public Event MouseLeftDown(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button is released.
   ''' </summary>
   Public Event MouseLeftUp(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button is double-clicked.
   ''' </summary>
   Public Event MouseLeftDoubleClick(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button is pressed.
   ''' </summary>
   Public Event MouseRightDown(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button is released.
   ''' </summary>
   Public Event MouseRightUp(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button is double-clicked.
   ''' </summary>
   Public Event MouseRightDoubleClick(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button is pressed.
   ''' </summary>
   Public Event MouseMiddleDown(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button is released.
   ''' </summary>
   Public Event MouseMiddleUp(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button is double-clicked.
   ''' </summary>
   Public Event MouseMiddleDoubleClick(ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when [mouse move].
   ''' </summary>
   Public Event MouseWheel(ByVal MouseLocation As Point,
                           ByVal WheelDirection As WheelDirection)

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Initializes a new instance of this class.
   ''' </summary>
   Public Sub New()

       MouseHookDelegate = New MouseProcDelegate(AddressOf MouseProc)

       MouseHook = SetWindowsHookEx(HookType.WH_MOUSE_LL,
                                    MouseHookDelegate,
                                    Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)
   End Sub

#End Region

#Region " Protected Methods "

   ''' <summary>
   ''' Allows an object to try to free resources
   ''' and perform other cleanup operations before it is reclaimed by garbage collection.
   ''' </summary>
   Protected Overrides Sub Finalize()

       UnhookWindowsHookEx(MouseHook)
       MyBase.Finalize()

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Processes the mouse windows messages and raises it's corresponding events.
   ''' </summary>
   ''' <returns>System.Int32.</returns>
   Private Function MouseProc(ByVal nCode As Integer,
                              ByVal wParam As Integer,
                              ByRef lParam As MSLLHOOKSTRUCT
   ) As Integer

       If nCode = 0 Then

           Select Case wParam

               Case MouseWindowsMessages.WM_MOUSEMOVE
                   RaiseEvent MouseMove(lParam.pt)

               Case MouseWindowsMessages.WM_LBUTTONDOWN
                   RaiseEvent MouseLeftDown(lParam.pt)

               Case MouseWindowsMessages.WM_LBUTTONUP
                   RaiseEvent MouseLeftUp(lParam.pt)

               Case MouseWindowsMessages.WM_LBUTTONDBLCLK
                   RaiseEvent MouseLeftDoubleClick(lParam.pt)

               Case MouseWindowsMessages.WM_RBUTTONDOWN
                   RaiseEvent MouseRightDown(lParam.pt)

               Case MouseWindowsMessages.WM_RBUTTONUP
                   RaiseEvent MouseRightUp(lParam.pt)

               Case MouseWindowsMessages.WM_RBUTTONDBLCLK
                   RaiseEvent MouseRightDoubleClick(lParam.pt)

               Case MouseWindowsMessages.WM_MBUTTONDOWN
                   RaiseEvent MouseMiddleDown(lParam.pt)

               Case MouseWindowsMessages.WM_MBUTTONUP
                   RaiseEvent MouseMiddleUp(lParam.pt)

               Case MouseWindowsMessages.WM_MBUTTONDBLCLK
                   RaiseEvent MouseMiddleDoubleClick(lParam.pt)

               Case MouseWindowsMessages.WM_MOUSEWHEEL
                   Dim wDirection As WheelDirection
                   If lParam.mouseData < 0 Then
                       wDirection = WheelDirection.WheelDown
                   Else
                       wDirection = WheelDirection.WheelUp
                   End If
                   RaiseEvent MouseWheel(lParam.pt, wDirection)

           End Select

       End If

       Return CallNextHookEx(MouseHook, nCode, wParam, lParam)

   End Function

#End Region

End Class

#End Region








AgnesBlack

perdona mi ignorancia pero en si, con esto se puede grabar los eventos del mouse??

engel lex

si puedes, grabar y simular por lo que veo... pero esto como tal no es un programa, es una "librería" para usar en tu codigo
El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.

Eleкtro

#3
El código puede subscribirse a los eventos del mouse, eso significa que si, puedes grabar cada acontecimiento y el orden de ellos, pero claro, eso requieriría hacer unas modificaciones para que el código se adapten a tus necesidades que "graben" los eventos en un objeto o archivo que contenga ese "set" de eventos, y lo mismo que para reproducir esas acciones.

Hace tiempo escribí un código para automatizar ambas tareas, la de grabar y la de reproducir, pero es un código que no reviso desde hace mucho tiempo, lo escribí cuando me estuve iniciando en .NET y usé técnicas inapropiadas (un timer) para grabar los eventos así que puede tener sus fallos, de todas formas te dejo el código por si te sirve:

Código (vbnet) [Seleccionar]

#Region " Record Mouse Class "

' [ Record Mouse Functions ]
'
' // By Elektro H@cker
'
' Examples :
' Record_Mouse.Start_Record()
' Record_Mouse.Stop_Record()
' Record_Mouse.Play() : While Not Record_Mouse.Play_Is_Completed : Application.DoEvents() : End While
' Record_Mouse.Mouse_Speed = 50

Public Class Record_Mouse

   ''' <summary>
   ''' Sets the speed of recording/playing the mouse actions.
   ''' Default value is 25.
   ''' </summary>
   Public Shared Mouse_Speed As Long = 30L

   ''' <summary>
   ''' Gets the status pf the current mouse play.
   ''' False = Mouse task is still playing.
   ''' True = Mouse task play is done.
   ''' </summary>
   Public Shared Play_Is_Completed As Boolean

   ' Where the mouse coordenates will be stored:
   Private Shared Coordenates_List As New List(Of Point)

   ' Where the mouse clicks will be stored:
   Private Shared Clicks_Dictionary As New Dictionary(Of Long, MouseButton)

   ' Timer to record the mouse:
   Private Shared WithEvents Record_Timer As New Timer

   ' Button click count to rec/play clicks:
   Private Shared Click_Count As Int32 = 0

   ' Thread to reproduce the mouse actions:
   Private Shared Thread_MousePlay_Var As System.Threading.Thread = New Threading.Thread(AddressOf Thread_MousePlay)

   ' API to record the current mouse button state:
   Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

   ' API to reproduce a mouse button click:
   Private Declare Sub Mouse_Event Lib "User32" Alias "mouse_event" (ByVal dwFlags As MouseButton, ByVal dx As Integer, ByVal dy As Integer, ByVal dwData As Integer, ByVal dwExtraInfo As Integer)

   ' GetAsyncKeyState buttons status
   Private Shared Last_ClickState_Left As Long = -1L
   Private Shared Last_ClickState_Right As Long = -1L
   Private Shared Last_ClickState_Middle As Long = -1L

   Enum MouseButton

       Left_Down = &H2    ' Left button (hold)
       Left_Up = &H4      ' Left button (release)

       Right_Down = &H8   ' Right button (hold)
       Right_Up = &H10    ' Right button (release)

       Middle_Down = &H20 ' Middle button (hold)
       Middle_Up = &H40   ' Middle button (release)

       Left               ' Left   button (press)
       Right              ' Right  button (press)
       Middle             ' Middle button (press)

   End Enum

   ''' <summary>
   ''' Starts recording the mouse actions over the screen.
   ''' It records the position of the mouse and left/right button clicks.
   ''' </summary>
   Public Shared Sub Start_Record()

       ' Reset vars:
       Play_Is_Completed = False
       Coordenates_List.Clear() : Clicks_Dictionary.Clear()
       Last_ClickState_Left = -1 : Last_ClickState_Right = -1 : Last_ClickState_Middle = -1
       Click_Count = 0

       ' Set Mouse Speed
       Record_Timer.Interval = Mouse_Speed

       ' Start Recording:
       Record_Timer.Start()

   End Sub

   ''' <summary>
   ''' Stop recording the mouse actions.
   ''' </summary>
   Public Shared Sub Stop_Record()
       Record_Timer.Stop()
   End Sub

   ''' <summary>
   ''' Reproduce the mouse actions.
   ''' </summary>
   Public Shared Sub Play()
       Thread_MousePlay_Var = New Threading.Thread(AddressOf Thread_MousePlay)
       Thread_MousePlay_Var.IsBackground = True
       Thread_MousePlay_Var.Start()
   End Sub

   ' Procedure used to store the mouse actions
   Private Shared Sub Record_Timer_Tick(sender As Object, e As EventArgs) Handles Record_Timer.Tick

       Coordenates_List.Add(Control.MousePosition)

       ' Record Left click
       If Not Last_ClickState_Left = GetAsyncKeyState(1) Then
           Last_ClickState_Left = GetAsyncKeyState(1)
           If GetAsyncKeyState(1) = 32768 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Down)
           ElseIf GetAsyncKeyState(1) = 0 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Left_Up)
           End If
       End If

       ' Record Right click
       If Not Last_ClickState_Right = GetAsyncKeyState(2) Then
           Last_ClickState_Right = GetAsyncKeyState(2)
           If GetAsyncKeyState(2) = 32768 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Down)
           ElseIf GetAsyncKeyState(2) = 0 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Right_Up)
           End If
       End If

       ' Record Middle click
       If Not Last_ClickState_Middle = GetAsyncKeyState(4) Then
           Last_ClickState_Middle = GetAsyncKeyState(4)
           If GetAsyncKeyState(4) = 32768 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Down)
           ElseIf GetAsyncKeyState(4) = 0 Then
               Click_Count += 1
               Coordenates_List.Add(Nothing)
               Clicks_Dictionary.Add(Click_Count, MouseButton.Middle_Up)
           End If
       End If

   End Sub

   ' Procedure to play a mouse button (click)
   Private Shared Sub Mouse_Click(ByVal MouseButton As MouseButton)
       Select Case MouseButton
           Case MouseButton.Left : Mouse_Event(MouseButton.Left_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Left_Up, 0, 0, 0, 0)
           Case MouseButton.Right : Mouse_Event(MouseButton.Right_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Right_Up, 0, 0, 0, 0)
           Case MouseButton.Middle : Mouse_Event(MouseButton.Middle_Down, 0, 0, 0, 0) : Mouse_Event(MouseButton.Middle_Up, 0, 0, 0, 0)
           Case Else : Mouse_Event(MouseButton, 0, 0, 0, 0)
       End Select
   End Sub

   ' Thread used for reproduce the mouse actions
   Private Shared Sub Thread_MousePlay()

       Click_Count = 0
       Clicks_Dictionary.Item(0) = Nothing

       For Each Coordenate In Coordenates_List

           Threading.Thread.Sleep(Mouse_Speed)

           If Coordenate = Nothing Then
               Click_Count += 1
               If Click_Count > 1 Then
                   Mouse_Click(Clicks_Dictionary.Item(Click_Count))
               End If
           Else
               Cursor.Position = Coordenate
           End If

       Next

       Mouse_Click(MouseButton.Left_Up)
       Mouse_Click(MouseButton.Right_Up)
       Mouse_Click(MouseButton.Middle_Up)

       Play_Is_Completed = True

   End Sub

End Class

#End Region












Eleкtro

El código que posteé hace tiempo (en el primer mensaje de este hilo) tenia unos fallos de los que no me percaté, he estado actualizando y corrigiendo el código ya que va a formar parte de la aplicación que presentaré en el EHN-DEv.

Aquí les dejo el código actualizado, estoy seguro que a alguien le servirá ya que a muchos nos apasiona los global-system hooks para Keyloggers y demás :) :

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-25-2014
' ***********************************************************************
' <copyright file="MouseHook.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Instructions "

' Go to page:
' Project > Properties > Debug
'
' Then uncheck the option:
' "Enable the Visual Studio Hosting Process"

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.InteropServices

#End Region

#Region " MouseHook "

''' <summary>
''' A low level mouse hook class that captures mouse events.
''' </summary>
Friend NotInheritable Class MouseHook : Implements IDisposable

#Region " P/Invoke "

   ''' <summary>
   ''' Platform Invocation methods (P/Invoke), access unmanaged code.
   ''' This class does not suppress stack walks for unmanaged code permission.
   ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
   ''' This class is for methods that can be used anywhere because a stack walk will be performed.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
   ''' </summary>
   Protected NotInheritable Class NativeMethods

#Region " Methods "

       ''' <summary>
       ''' Passes the hook information to the next hook procedure in the current hook chain.
       ''' A hook procedure can call this function either before or after processing the hook information.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="idHook">
       ''' This parameter is ignored.
       ''' </param>
       ''' <param name="nCode">
       ''' The hook code passed to the current hook procedure.
       ''' The next hook procedure uses this code to determine how to process the hook information.
       ''' </param>
       ''' <param name="wParam">
       ''' The wParam value passed to the current hook procedure.
       ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
       ''' </param>
       ''' <param name="lParam">
       ''' The lParam value passed to the current hook procedure.
       ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
       ''' </param>
       ''' <returns>
       ''' This value is returned by the next hook procedure in the chain.
       ''' The current hook procedure must also return this value.
       ''' The meaning of the return value depends on the hook type.
       ''' For more information, see the descriptions of the individual hook procedures.
       ''' </returns>
       <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
       Friend Shared Function CallNextHookEx(
              ByVal idHook As IntPtr,
              ByVal nCode As Integer,
              ByVal wParam As IntPtr,
              ByVal lParam As IntPtr
       ) As IntPtr
       End Function

       ''' <summary>
       ''' Installs an application-defined hook procedure into a hook chain.
       ''' You would install a hook procedure to monitor the system for certain types of events.
       ''' These events are associated either with a specific thread
       ''' or with all threads in the same desktop as the calling thread.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="idHook">
       ''' The type of hook procedure to be installed.
       ''' </param>
       ''' <param name="lpfn">
       ''' A pointer to the hook procedure.
       ''' If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process,
       ''' the lpfn parameter must point to a hook procedure in a DLL.
       ''' Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
       ''' </param>
       ''' <param name="hInstance">
       ''' A handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
       ''' The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
       ''' the current process and if the hook procedure is within the code associated with the current process.
       ''' </param>
       ''' <param name="threadId">
       ''' The identifier of the thread with which the hook procedure is to be associated.
       ''' For desktop apps, if this parameter is zero, the hook procedure is associated
       ''' with all existing threads running in the same desktop as the calling thread.
       ''' </param>
       ''' <returns>
       ''' If the function succeeds, the return value is the handle to the hook procedure.
       ''' If the function fails, the return value is NULL.
       ''' </returns>
       <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
       Friend Shared Function SetWindowsHookEx(
              ByVal idHook As HookType,
              ByVal lpfn As LowLevelMouseProcDelegate,
              ByVal hInstance As IntPtr,
              ByVal threadId As UInteger
       ) As IntPtr
       End Function

       ''' <summary>
       ''' Removes a hook procedure installed in a hook chain by the 'SetWindowsHookEx' function.
       ''' For more info see here:
       ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644993%28v=vs.85%29.aspx
       ''' </summary>
       ''' <param name="idHook">
       ''' A handle to the hook to be removed.
       ''' This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
       ''' </param>
       ''' <returns>
       ''' If the function succeeds, the return value is nonzero.
       ''' If the function fails, the return value is zero.
       ''' </returns>
       <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
       Friend Shared Function UnhookWindowsHookEx(
              ByVal idHook As IntPtr
       ) As Boolean
       End Function

       ''' <summary>
       ''' Retrieves the current double-click time for the mouse.
       ''' A double-click is a series of two clicks of the mouse button,
       ''' the second occurring within a specified time after the first.
       ''' The double-click time is the maximum number of milliseconds that may occur
       ''' between the first and second click of a double-click.
       ''' The maximum double-click time is 5000 milliseconds.
       ''' </summary>
       ''' <returns>
       ''' The return value specifies the current double-click time, in milliseconds.
       ''' The maximum return value is 5000 milliseconds.
       ''' </returns>
       <DllImport("user32.dll", CharSet:=CharSet.Auto)>
       Friend Shared Function GetDoubleClickTime() As Integer
       End Function

#End Region

#Region " Enumerations "

       ''' <summary>
       ''' Indicates a type of Hook procedure to be installed.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Enum used in 'idHook' parameter of 'SetWindowsHookEx' function")>
       Friend Enum HookType As Integer

           ' **************************************
           ' This enumeration is partially defined.
           ' **************************************

           ''' <summary>
           ''' Installs a hook procedure that monitors low-level mouse input events.
           ''' For more information, see the LowLevelMouseProc hook procedure.
           ''' </summary>
           WH_MOUSE_LL = 14I

       End Enum

#End Region

#Region " Structures "

       ''' <summary>
       ''' Contains information about a low-level mouse input event.
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644970%28v=vs.85%29.aspx
       ''' </summary>
       <Description("Structure used in 'lParam' parameter of 'CallNextHookEx' function")>
       Friend Structure MSLLHOOKSTRUCT

           ''' <summary>
           ''' The ptThe x- and y-coordinates of the cursor, in screen coordinates.
           ''' </summary>
           Friend pt As Point

           ''' <summary>
           ''' If the message is 'WM_MOUSEWHEEL', the high-order word of this member is the wheel delta.
           ''' The low-order word is reserved.
           ''' A positive value indicates that the wheel was rotated forward, away from the user;
           ''' a negative value indicates that the wheel was rotated backward, toward the user.
           ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
           ''' </summary>
           Friend mouseData As Integer

           ''' <summary>
           ''' The event-injected flag.
           ''' </summary>
           Friend flags As UInteger

           ''' <summary>
           ''' The time stamp for this message.
           ''' </summary>
           Friend time As UInteger

           ''' <summary>
           ''' Additional information associated with the message.
           ''' </summary>
           Friend dwExtraInfo As IntPtr

       End Structure

#End Region

#Region " Delegates "

       ''' <summary>
       ''' Delegate LowLevelMouseProc
       ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
       ''' </summary>
       ''' <returns>
       ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
       ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
       ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
       ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
       ''' and may behave incorrectly as a result.
       ''' If the hook procedure processed the message,
       ''' it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.
       ''' </returns>
       Friend Delegate Function LowLevelMouseProcDelegate(
               ByVal nCode As IntPtr,
               ByVal wParam As IntPtr,
               ByRef lParam As NativeMethods.MSLLHOOKSTRUCT
       ) As IntPtr

#End Region

#Region " Hidden Methods "

       ''' <summary>
       ''' Determines whether the specified System.Object instances are considered equal.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Public Shadows Sub Equals()
       End Sub

       ''' <summary>
       ''' Determines whether the specified System.Object instances are the same instance.
       ''' </summary>
       <EditorBrowsable(EditorBrowsableState.Never)>
       Private Shadows Sub ReferenceEquals()
       End Sub

#End Region

   End Class

#End Region

#Region " Objects "

   ''' <summary>
   ''' Handle to the hook procedure.
   ''' </summary>
   Private MouseHook As IntPtr

   ''' <summary>
   ''' The mouse hook delegate.
   ''' </summary>
   Private MouseHookDelegate As NativeMethods.LowLevelMouseProcDelegate

#End Region

#Region " Properties "

   ''' <summary>
   ''' ** ONLY FOR TESTING PURPOSES **
   ''' Gets or sets a value indicating whether to suppress the last MouseUp event of
   ''' the specified clicked button when a double-click fires.
   '''
   ''' If this value is set to <c>true</c>, the application will send the events in this order for a Double-Click:
   ''' MouseDown, MouseUp, MouseDown, MouseDoubleClick
   '''
   ''' If this value is set to <c>false</c>, the application will send the events in this order for a Double-Click:
   ''' MouseDown, MouseUp, MouseDown, MouseUp, MouseDoubleClick
   '''
   ''' </summary>
   ''' <value><c>true</c> if MouseUp event is suppressed; otherwise <c>false</c>.</value>
   Friend Property SuppressMouseUpEventWhenDoubleClick As Boolean = False

#End Region

#Region " Enumerations "

   ''' <summary>
   ''' Indicates a Windows Message related to a mouse events.
   ''' For more info see here:
   ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ff468877%28v=vs.85%29.aspx
   ''' </summary>
   Private Enum MouseMessages As UInteger

       ''' <summary>
       ''' Posted to a window when the cursor moves.
       ''' If the mouse is not captured, the message is posted to the window that contains the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MOUSEMOVE = &H200UI

       ''' <summary>
       ''' Posted when the user presses the left mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_LBUTTONDOWN = &H201UI

       ''' <summary>
       ''' Posted when the user releases the left mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_LBUTTONUP = &H202UI

       ''' <summary>
       ''' Posted when the user presses the right mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_RBUTTONDOWN = &H204UI

       ''' <summary>
       ''' Posted when the user releases the right mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_RBUTTONUP = &H205UI

       ''' <summary>
       ''' Posted when the user presses the middle mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MBUTTONDOWN = &H207UI

       ''' <summary>
       ''' Posted when the user releases the middle mouse button while the cursor is in the client area of a window.
       ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
       ''' Otherwise, the message is posted to the window that has captured the mouse
       ''' </summary>
       WM_MBUTTONUP = &H208UI

       ''' <summary>
       ''' Sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated.
       ''' The DefWindowProc function propagates the message to the window's parent.
       ''' There should be no internal forwarding of the message,
       ''' since DefWindowProc propagates it up the parent chain until it finds a window that processes it.
       ''' </summary>
       WM_MOUSEWHEEL = &H20AUI

   End Enum

   ''' <summary>
   ''' Indicates the whell direction of the mouse.
   ''' </summary>
   Public Enum WheelDirection As Integer

       ''' <summary>
       ''' The wheel is moved up.
       ''' </summary>
       WheelUp = 1

       ''' <summary>
       ''' The wheel is moved down.
       ''' </summary>
       WheelDown = 2

   End Enum

#End Region

#Region " Events "

   ''' <summary>
   ''' Occurs when the mouse moves.
   ''' </summary>
   Friend Event MouseMove(ByVal sender As Object,
                          ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button is pressed.
   ''' </summary>
   Friend Event MouseLeftDown(ByVal sender As Object,
                              ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button is released.
   ''' </summary>
   Friend Event MouseLeftUp(ByVal sender As Object,
                            ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse left button performs a double-click.
   ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
   ''' </summary>
   Friend Event MouseLeftDoubleClick(ByVal sender As Object,
                                     ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button is pressed.
   ''' </summary>
   Friend Event MouseRightDown(ByVal sender As Object,
                               ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button is released.
   ''' </summary>
   Friend Event MouseRightUp(ByVal sender As Object,
                             ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse right button performs a double-click.
   ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
   ''' </summary>
   Friend Event MouseRightDoubleClick(ByVal sender As Object,
                                      ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button is pressed.
   ''' </summary>
   Friend Event MouseMiddleDown(ByVal sender As Object,
                                ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button is released.
   ''' </summary>
   Friend Event MouseMiddleUp(ByVal sender As Object,
                              ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse middle button performs a double-click.
   ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
   ''' </summary>
   Friend Event MouseMiddleDoubleClick(ByVal sender As Object,
                                       ByVal MouseLocation As Point)

   ''' <summary>
   ''' Occurs when the mouse wheel is moved up or down.
   ''' </summary>
   Friend Event MouseWheel(ByVal sender As Object,
                           ByVal MouseLocation As Point,
                           ByVal WheelDirection As WheelDirection)

#End Region

#Region " Constructors "

   ''' <summary>
   ''' Prevents a default instance of the <see cref="MouseHook"/> class from being created.
   ''' </summary>
   Private Sub New()
   End Sub

   ''' <summary>
   ''' Initializes a new instance of the <see cref="MouseHook"/> class.
   ''' </summary>
   ''' <param name="AutoStart">
   ''' If set to <c>true</c>, the Hook starts instantly for this <see cref="MouseHook"/> instance.
   ''' </param>
   Friend Sub New(Optional ByVal AutoStart As Boolean = False)

       If AutoStart Then
           Me.[Start]()
       End If

   End Sub

#End Region

#Region " Public Methods "

   ''' <summary>
   ''' Starts the Mouse Hook, then start processing messages to fire events.
   ''' </summary>
   Friend Sub [Start]()

       Me.MouseHookDelegate = New NativeMethods.LowLevelMouseProcDelegate(AddressOf LowLevelMouseProc)

       Try
           Me.MouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE_LL,
                                                         Me.MouseHookDelegate,
                                                         Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)

       Catch ex As Exception
           Throw

       End Try

   End Sub

   ''' <summary>
   ''' Stops the Mouse Hook and free all resources, then stop processing messages to fire events.
   ''' </summary>
   Friend Sub [Stop]()

       Me.Finalize()

   End Sub

#End Region

#Region " Private Methods "

   ''' <summary>
   ''' Processes the mouse windows messages and raises it's corresponding events.
   ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
   ''' </summary>
   ''' <param name="nCode">
   ''' A code the hook procedure uses to determine how to process the message.
   ''' If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function
   ''' without further processing and should return the value returned by CallNextHookEx.
   ''' </param>
   ''' <param name="wParam">The identifier of the mouse message.</param>
   ''' <param name="lParam"> A pointer to an <see cref="NativeMethods.MSLLHOOKSTRUCT"/> structure.</param>
   ''' <returns>
   ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
   ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
   ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
   ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
   ''' and may behave incorrectly as a result.
   ''' If the hook procedure processed the message,
   ''' it may return a nonzero value to prevent the system from passing the
   ''' message to the rest of the hook chain or the target window procedure.
   ''' </returns>
   Private Function LowLevelMouseProc(ByVal nCode As Integer,
                                      ByVal wParam As MouseMessages,
                                      ByRef lParam As NativeMethods.MSLLHOOKSTRUCT) As Integer

       Static LeftClickTime As Integer = 0I ' Determines a left button double-click.
       Static RightClickTime As Integer = 0I ' Determines a right button double-click.
       Static MiddleClickTime As Integer = 0I ' Determines a middle button double-click.

       If nCode = 0I Then

           Select Case wParam

               Case MouseMessages.WM_MOUSEMOVE
                   RaiseEvent MouseMove(Me, lParam.pt)

               Case MouseMessages.WM_LBUTTONDOWN
                   RaiseEvent MouseLeftDown(Me, lParam.pt)

               Case MouseMessages.WM_LBUTTONUP
                   If LeftClickTime <> 0 Then
                       LeftClickTime = Environment.TickCount() - LeftClickTime
                   End If

                   If (LeftClickTime <> 0) AndAlso (LeftClickTime < NativeMethods.GetDoubleClickTime()) Then
                       LeftClickTime = 0
                       If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                           RaiseEvent MouseLeftUp(Me, lParam.pt)
                       End If
                       RaiseEvent MouseLeftDoubleClick(Me, lParam.pt)

                   Else
                       LeftClickTime = Environment.TickCount()
                       RaiseEvent MouseLeftUp(Me, lParam.pt)

                   End If

               Case MouseMessages.WM_RBUTTONDOWN
                   RaiseEvent MouseRightDown(Me, lParam.pt)

               Case MouseMessages.WM_RBUTTONUP
                   If RightClickTime <> 0 Then
                       RightClickTime = Environment.TickCount() - RightClickTime
                   End If

                   If (RightClickTime <> 0) AndAlso (RightClickTime < NativeMethods.GetDoubleClickTime()) Then
                       RightClickTime = 0
                       If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                           RaiseEvent MouseRightUp(Me, lParam.pt)
                       End If
                       RaiseEvent MouseRightDoubleClick(Me, lParam.pt)

                   Else
                       RightClickTime = Environment.TickCount()
                       RaiseEvent MouseRightUp(Me, lParam.pt)

                   End If

               Case MouseMessages.WM_MBUTTONDOWN
                   RaiseEvent MouseMiddleDown(Me, lParam.pt)

               Case MouseMessages.WM_MBUTTONUP
                   If MiddleClickTime <> 0 Then
                       MiddleClickTime = Environment.TickCount() - MiddleClickTime
                   End If

                   If (MiddleClickTime <> 0) AndAlso (MiddleClickTime < NativeMethods.GetDoubleClickTime()) Then
                       MiddleClickTime = 0
                       If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                           RaiseEvent MouseMiddleUp(Me, lParam.pt)
                       End If
                       RaiseEvent MouseMiddleDoubleClick(Me, lParam.pt)

                   Else
                       MiddleClickTime = Environment.TickCount()
                       RaiseEvent MouseMiddleUp(Me, lParam.pt)

                   End If

               Case MouseMessages.WM_MOUSEWHEEL
                   RaiseEvent MouseWheel(Me, lParam.pt, If(lParam.mouseData < 0,
                                                           WheelDirection.WheelDown,
                                                           WheelDirection.WheelUp))

               Case Else
                   Exit Select ' Do Nothing

           End Select

           Return 0

       ElseIf nCode < 0I Then

           ' Initialize unmanged memory to hold the 'MSLLHOOKSTRUCT' structure.
           Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(lParam))

           Try ' MSDN Documentation: http://msdn.microsoft.com/en-us/library/vstudio/4ca6d5z7%28v=vs.100%29.aspx

               ' Copy the struct to unmanaged memory.
               Marshal.StructureToPtr(lParam, pnt, False)

               ' Return
               Return NativeMethods.CallNextHookEx(MouseHook, nCode, wParam, pnt)

           Finally
               ' Free the unmanaged memory.
               Marshal.FreeHGlobal(pnt)
           End Try

       Else ' nCode > 0

           Return -1I

       End If

   End Function

#End Region

#Region " Hidden Methods "

   ''' <summary>
   ''' Serves as a hash function for a particular type.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub GetHashCode()
   End Sub

   ''' <summary>
   ''' Gets the System.Type of the current instance.
   ''' </summary>
   ''' <returns>The exact runtime type of the current instance.</returns>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Function [GetType]()
       Return Me.GetType
   End Function

   ''' <summary>
   ''' Determines whether the specified System.Object instances are considered equal.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub Equals()
   End Sub

   ''' <summary>
   ''' Determines whether the specified System.Object instances are the same instance.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Private Shadows Sub ReferenceEquals()
   End Sub

   ''' <summary>
   ''' Returns a String that represents the current object.
   ''' </summary>
   <EditorBrowsable(EditorBrowsableState.Never)>
   Public Shadows Sub ToString()
   End Sub

#End Region

#Region "IDisposable Support"

   ''' <summary>
   ''' Flag to detect redundant calls at <see cref="Dispose"/> method.
   ''' </summary>
   Private disposedValue As Boolean

   ''' <summary>
   ''' Releases unmanaged and optionally managed resources.
   ''' </summary>
   ''' <param name="disposing">
   ''' <c>true</c> to release both managed and unmanaged resources;
   ''' <c>false</c> to release only unmanaged resources.
   ''' </param>
   Protected Sub Dispose(ByVal disposing As Boolean)

       If Not Me.disposedValue Then

           If disposing Then ' Dispose managed state (managed objects).

           Else ' Free unmanaged resources (unmanaged objects).
               NativeMethods.UnhookWindowsHookEx(Me.MouseHook)

           End If

       End If

       Me.disposedValue = True

   End Sub

   ''' <summary>
   ''' Allows an object to try to free resources
   ''' and perform other cleanup operations before it is reclaimed by garbage collection.
   ''' </summary>
   Protected Overrides Sub Finalize()

       ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

       Me.Dispose(disposing:=False)
       MyBase.Finalize()

   End Sub

   ''' <summary>
   ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
   ''' </summary>
   Private Sub Dispose() Implements IDisposable.Dispose

       ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

       Me.Dispose(disposing:=True)
       GC.SuppressFinalize(obj:=Me)

   End Sub

#End Region

End Class

#End Region









Eleкtro

Hago este doble post (y perdón con antelación) para mostrar un ejemplo de uso, ya que no cabe más arriba.

Código (vbnet) [Seleccionar]
Public Class Form1

    ''' <summary>
    ''' A low level mouse hook that intercepts mouse events.
    ''' </summary>
    Friend WithEvents MouseEvents As New MouseHook(AutoStart:=False) With {.SuppressMouseUpEventWhenDoubleClick = False}

    ''' <summary>
    ''' Handles the Load event of the Form1.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        ' Start the Mouse Hook.
        Me.MouseEvents.[Start]()

    End Sub

    ''' <summary>
    ''' Handles the FormClosing event of the Form1.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="FormClosingEventArgs"/> instance containing the event data.</param>
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) _
    Handles MyBase.FormClosing

        ' Stop and free the Mouse Hook resources.
        Me.MouseEvents.[Stop]()

    End Sub

    ''' <summary>
    ''' Handles the 'MouseMove' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseMove(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseMove

        Debug.WriteLine(String.Format("Mouse Moved To: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseLeftDown' event of the MouseHook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseLeftDown(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseLeftDown

        Debug.WriteLine(String.Format("Mouse Left Down At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseLeftUp' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseLeftUp(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseLeftUp

        Debug.WriteLine(String.Format("Mouse Left Up At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseRightDown' event of the MouseHook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseRightDown(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseRightDown

        Debug.WriteLine(String.Format("Mouse Right Down At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseRightUp' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseRightUp(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseRightUp

        Debug.WriteLine(String.Format("Mouse Right Up At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseMiddleDown' event of the MouseHook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseMiddleDown(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseMiddleDown

        Debug.WriteLine(String.Format("Mouse Middle Down At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseMiddleUp' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseMiddleUp(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseMiddleUp

        Debug.WriteLine(String.Format("Mouse Middle Up At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseLeftDoubleClick' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseLeftDoubleClick(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseLeftDoubleClick

        Debug.WriteLine(String.Format("Mouse Left Double-Click At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseRightDoubleClick' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseRightDoubleClick(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseRightDoubleClick

        Debug.WriteLine(String.Format("Mouse Right Double-Click At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseMiddleDoubleClick' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    Private Sub MouseEvents_MouseMiddleDoubleClick(ByVal sender As Object, ByVal MouseLocation As Point) _
    Handles MouseEvents.MouseMiddleDoubleClick

        Debug.WriteLine(String.Format("Mouse Middle Double-Click At: x={0}, y={1}",
                                      CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

    ''' <summary>
    ''' Handles the 'MouseWheel' event of the Mouse Hook.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="MouseLocation">Contains the mouse [X,Y] coordinates where the event fired.</param>
    ''' <param name="WheelDirection">Contains the wheel direction (WheelUp or WheelDown).</param>
    Private Sub MouseEvents_MouseWheel(ByVal sender As Object,
                                       ByVal MouseLocation As Point,
                                       ByVal WheelDirection As MouseHook.WheelDirection) _
    Handles MouseEvents.MouseWheel

        Debug.WriteLine(String.Format("Mouse Whell ({0}) At: x={1}, y={2}",
                                      WheelDirection.ToString, CStr(MouseLocation.X), CStr(MouseLocation.Y)))

    End Sub

End Class








Eleкtro

un último repaso definitivo a esta Class, para fijar un pequeño problema con las coordenadas.

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-26-2014
' ***********************************************************************
' <copyright file="MouseHook.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Instructions "

' Go to page:
' Project > Properties > Debug
'
' Then uncheck the option:
' "Enable the Visual Studio Hosting Process"

#End Region

#Region " Usage Examples "

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.InteropServices

#End Region

#Region " MouseHook "

''' <summary>
''' A low level mouse hook that processes mouse input events.
''' </summary>
Friend NotInheritable Class MouseHook : Implements IDisposable

#Region " P/Invoke "

    ''' <summary>
    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
    ''' This class does not suppress stack walks for unmanaged code permission.
    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
    ''' </summary>
    Protected NotInheritable Class NativeMethods

#Region " Methods "

        ''' <summary>
        ''' Passes the hook information to the next hook procedure in the current hook chain.
        ''' A hook procedure can call this function either before or after processing the hook information.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' This parameter is ignored.
        ''' </param>
        ''' <param name="nCode">
        ''' The hook code passed to the current hook procedure.
        ''' The next hook procedure uses this code to determine how to process the hook information.
        ''' </param>
        ''' <param name="wParam">
        ''' The wParam value passed to the current hook procedure.
        ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
        ''' </param>
        ''' <param name="lParam">
        ''' The lParam value passed to the current hook procedure.
        ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
        ''' </param>
        ''' <returns>
        ''' This value is returned by the next hook procedure in the chain.
        ''' The current hook procedure must also return this value.
        ''' The meaning of the return value depends on the hook type.
        ''' For more information, see the descriptions of the individual hook procedures.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function CallNextHookEx(
               ByVal idHook As IntPtr,
               ByVal nCode As Integer,
               ByVal wParam As IntPtr,
               ByVal lParam As IntPtr
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Installs an application-defined hook procedure into a hook chain.
        ''' You would install a hook procedure to monitor the system for certain types of events.
        ''' These events are associated either with a specific thread
        ''' or with all threads in the same desktop as the calling thread.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' The type of hook procedure to be installed.
        ''' </param>
        ''' <param name="lpfn">
        ''' A pointer to the hook procedure.
        ''' If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process,
        ''' the lpfn parameter must point to a hook procedure in a DLL.
        ''' Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
        ''' </param>
        ''' <param name="hInstance">
        ''' A handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
        ''' The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
        ''' the current process and if the hook procedure is within the code associated with the current process.
        ''' </param>
        ''' <param name="threadId">
        ''' The identifier of the thread with which the hook procedure is to be associated.
        ''' For desktop apps, if this parameter is zero, the hook procedure is associated
        ''' with all existing threads running in the same desktop as the calling thread.
        ''' </param>
        ''' <returns>
        ''' If the function succeeds, the return value is the handle to the hook procedure.
        ''' If the function fails, the return value is NULL.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function SetWindowsHookEx(
               ByVal idHook As HookType,
               ByVal lpfn As LowLevelMouseProcDelegate,
               ByVal hInstance As IntPtr,
               ByVal threadId As UInteger
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Removes a hook procedure installed in a hook chain by the 'SetWindowsHookEx' function.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644993%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' A handle to the hook to be removed.
        ''' This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
        ''' </param>
        ''' <returns>
        ''' If the function succeeds, the return value is nonzero.
        ''' If the function fails, the return value is zero.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function UnhookWindowsHookEx(
               ByVal idHook As IntPtr
        ) As Boolean
        End Function

        ''' <summary>
        ''' Retrieves the current double-click time for the mouse.
        ''' A double-click is a series of two clicks of the mouse button,
        ''' the second occurring within a specified time after the first.
        ''' The double-click time is the maximum number of milliseconds that may occur
        ''' between the first and second click of a double-click.
        ''' The maximum double-click time is 5000 milliseconds.
        ''' </summary>
        ''' <returns>
        ''' The return value specifies the current double-click time, in milliseconds.
        ''' The maximum return value is 5000 milliseconds.
        ''' </returns>
        <DllImport("user32.dll", CharSet:=CharSet.Auto)>
        Friend Shared Function GetDoubleClickTime() As Integer
        End Function

#End Region

#Region " Enumerations "

        ''' <summary>
        ''' Indicates a type of Hook procedure to be installed.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Enum used in 'idHook' parameter of 'SetWindowsHookEx' function.")>
        Friend Enum HookType As UInteger

            ' **************************************
            ' This enumeration is partially defined.
            ' **************************************

            ''' <summary>
            ''' Installs a hook procedure that monitors low-level mouse input events.
            ''' For more information, see the LowLevelMouseProc hook procedure.
            ''' </summary>
            WH_MOUSE_LL = 14UI

        End Enum

        ''' <summary>
        ''' The event-injected flags.
        ''' An application can use the following values to test the flags.
        ''' Testing LLMHF_INJECTED (bit 0) will tell you whether the event was injected.
        ''' If it was, then testing LLMHF_LOWER_IL_INJECTED (bit 1) will tell you
        ''' whether or not the event was injected from a process running at lower integrity level.
        ''' </summary>
        <Flags()>
        <Description("Enum used in 'flags' parameter of 'MSLLHOOKSTRUCT' structure.")>
        Public Enum MSLLHOOKSTRUCTFlags As Integer

            ''' <summary>
            ''' Test the event-injected (from any process) flag.
            ''' </summary>
            LLMHF_INJECTED = 1

            ''' <summary>
            ''' Test the event-injected (from a process running at lower integrity level) flag.
            ''' </summary>
            LLMHF_LOWER_IL_INJECTED = 2

        End Enum

#End Region

#Region " Structures "

        ''' <summary>
        ''' The POINT structure defines the x- and y- coordinates of a point.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Structure used in 'pt' parameter of 'MSLLHOOKSTRUCT' structure.")>
        <StructLayout(LayoutKind.Sequential)>
        Friend Structure POINT

            ''' <summary>
            ''' The x-coordinate of the point.
            ''' </summary>
            Public X As Integer

            ''' <summary>
            ''' The y-coordinate of the point.
            ''' </summary>
            Public Y As Integer

        End Structure

        ''' <summary>
        ''' Contains information about a low-level mouse input event.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644970%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Structure used in 'lParam' parameter of 'CallNextHookEx' function.")>
        Friend Structure MSLLHOOKSTRUCT

            ''' <summary>
            ''' The ptThe x- and y-coordinates of the cursor, in screen coordinates.
            ''' </summary>
            Friend pt As NativeMethods.POINT

            ''' <summary>
            ''' If the message is 'WM_MOUSEWHEEL', the high-order word of this member is the wheel delta.
            ''' The low-order word is reserved.
            ''' A positive value indicates that the wheel was rotated forward, away from the user;
            ''' a negative value indicates that the wheel was rotated backward, toward the user.
            ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
            ''' </summary>
            Friend mouseData As Integer

            ''' <summary>
            ''' The event-injected flag.
            ''' </summary>
            Friend flags As MSLLHOOKSTRUCTFlags

            ''' <summary>
            ''' The time stamp for this message.
            ''' </summary>
            Friend time As UInteger

            ''' <summary>
            ''' Additional information associated with the message.
            ''' </summary>
            Friend dwExtraInfo As IntPtr

        End Structure

#End Region

#Region " Delegates "

        ''' <summary>
        ''' Delegate LowLevelMouseProc
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
        ''' </summary>
        ''' <returns>
        ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
        ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
        ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
        ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
        ''' and may behave incorrectly as a result.
        ''' If the hook procedure processed the message,
        ''' it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.
        ''' </returns>
        Friend Delegate Function LowLevelMouseProcDelegate(
                ByVal nCode As IntPtr,
                ByVal wParam As IntPtr,
                ByVal lParam As IntPtr
        ) As Integer

#End Region

#Region " Hidden Methods "

        ''' <summary>
        ''' Determines whether the specified System.Object instances are considered equal.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub Equals()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are the same instance.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Private Shadows Sub ReferenceEquals()
        End Sub

#End Region

    End Class

#End Region

#Region " Objects "

    ''' <summary>
    ''' Handle to the hook procedure.
    ''' </summary>
    Private MouseHook As IntPtr

    ''' <summary>
    ''' The mouse hook delegate.
    ''' </summary>
    Private MouseHookDelegate As NativeMethods.LowLevelMouseProcDelegate

#End Region

#Region " Properties "

    ''' <summary>
    ''' ** ONLY FOR TESTING PURPOSES **
    ''' Gets or sets a value indicating whether to suppress the last MouseUp event of
    ''' the specified clicked button when a double-click fires.
    '''
    ''' If this value is set to <c>true</c>, the application will send the events in this order for a Double-Click:
    ''' MouseDown, MouseUp, MouseDown, MouseDoubleClick
    '''
    ''' If this value is set to <c>false</c>, the application will send the events in this order for a Double-Click:
    ''' MouseDown, MouseUp, MouseDown, MouseUp, MouseDoubleClick
    '''
    ''' </summary>
    ''' <value><c>true</c> if MouseUp event is suppressed; otherwise <c>false</c>.</value>
    Friend Property SuppressMouseUpEventWhenDoubleClick As Boolean = False

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Indicates a Windows Message related to a mouse events.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ff468877%28v=vs.85%29.aspx
    ''' </summary>
    Private Enum MouseMessages As UInteger

        ''' <summary>
        ''' Posted to a window when the cursor moves.
        ''' If the mouse is not captured, the message is posted to the window that contains the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MOUSEMOVE = &H200UI

        ''' <summary>
        ''' Posted when the user presses the left mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONDOWN = &H201UI

        ''' <summary>
        ''' Posted when the user releases the left mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONUP = &H202UI

        ''' <summary>
        ''' Posted when the user presses the right mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONDOWN = &H204UI

        ''' <summary>
        ''' Posted when the user releases the right mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONUP = &H205UI

        ''' <summary>
        ''' Posted when the user presses the middle mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONDOWN = &H207UI

        ''' <summary>
        ''' Posted when the user releases the middle mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONUP = &H208UI

        ''' <summary>
        ''' Sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated.
        ''' The DefWindowProc function propagates the message to the window's parent.
        ''' There should be no internal forwarding of the message,
        ''' since DefWindowProc propagates it up the parent chain until it finds a window that processes it.
        ''' </summary>
        WM_MOUSEWHEEL = &H20AUI

    End Enum

    ''' <summary>
    ''' Indicates the whell direction of the mouse.
    ''' </summary>
    Public Enum WheelDirection As Integer

        ''' <summary>
        ''' The wheel is moved up.
        ''' </summary>
        WheelUp = 1

        ''' <summary>
        ''' The wheel is moved down.
        ''' </summary>
        WheelDown = 2

    End Enum

#End Region

#Region " Events "

    ''' <summary>
    ''' Occurs when the mouse moves.
    ''' </summary>
    Friend Event MouseMove(ByVal sender As Object,
                           ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is pressed.
    ''' </summary>
    Friend Event MouseLeftDown(ByVal sender As Object,
                               ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is released.
    ''' </summary>
    Friend Event MouseLeftUp(ByVal sender As Object,
                             ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseLeftDoubleClick(ByVal sender As Object,
                                      ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is pressed.
    ''' </summary>
    Friend Event MouseRightDown(ByVal sender As Object,
                                ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is released.
    ''' </summary>
    Friend Event MouseRightUp(ByVal sender As Object,
                              ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseRightDoubleClick(ByVal sender As Object,
                                       ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is pressed.
    ''' </summary>
    Friend Event MouseMiddleDown(ByVal sender As Object,
                                 ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is released.
    ''' </summary>
    Friend Event MouseMiddleUp(ByVal sender As Object,
                               ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseMiddleDoubleClick(ByVal sender As Object,
                                        ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse wheel is moved up or down.
    ''' </summary>
    Friend Event MouseWheel(ByVal sender As Object,
                            ByVal MouseLocation As Point,
                            ByVal WheelDirection As WheelDirection)

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Prevents a default instance of the <see cref="MouseHook"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="MouseHook"/> class.
    ''' </summary>
    ''' <param name="Install">
    ''' If set to <c>true</c>, the Hook starts initialized for this <see cref="MouseHook"/> instance.
    ''' </param>
    Friend Sub New(Optional ByVal Install As Boolean = False)

        If Install Then
            Me.Install()
        End If

    End Sub

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Installs the Mouse Hook, then start processing messages to fire events.
    ''' </summary>
    Friend Sub Install()

        Me.MouseHookDelegate = New NativeMethods.LowLevelMouseProcDelegate(AddressOf LowLevelMouseProc)

        Try
            Me.MouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE_LL,
                                                          Me.MouseHookDelegate,
                                                          Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)

        Catch ex As Exception
            Throw

        End Try

    End Sub

    ''' <summary>
    ''' Uninstalls the Mouse Hook and free all resources, then stop processing messages to fire events.
    ''' </summary>
    Friend Sub Uninstall()

        Me.Finalize()

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Processes the mouse windows messages and raises it's corresponding events.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="nCode">
    ''' A code the hook procedure uses to determine how to process the message.
    ''' If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function
    ''' without further processing and should return the value returned by CallNextHookEx.
    ''' </param>
    ''' <param name="wParam">The identifier of the mouse message.</param>
    ''' <param name="lParam"> A pointer to an <see cref="NativeMethods.MSLLHOOKSTRUCT"/> structure.</param>
    ''' <returns>
    ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
    ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
    ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
    ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
    ''' and may behave incorrectly as a result.
    ''' If the hook procedure processed the message,
    ''' it may return a nonzero value to prevent the system from passing the
    ''' message to the rest of the hook chain or the target window procedure.
    ''' </returns>
    Private Function LowLevelMouseProc(ByVal nCode As Integer,
                                       ByVal wParam As MouseMessages,
                                       ByVal lParam As IntPtr) As Integer

        Static LeftClickTime As Integer = 0I ' Determines a left button double-click.
        Static RightClickTime As Integer = 0I ' Determines a right button double-click.
        Static MiddleClickTime As Integer = 0I ' Determines a middle button double-click.

        If nCode = 0I Then

            Dim x As Integer
            Dim y As Integer

            Dim MouseStruct As NativeMethods.MSLLHOOKSTRUCT
            MouseStruct = CType(Marshal.PtrToStructure(lParam, MouseStruct.GetType()),
                                NativeMethods.MSLLHOOKSTRUCT)

            ' Fix X coordinate.
            Select Case MouseStruct.pt.X

                Case Is < 0I
                    x = 0I

                Case Is > SystemInformation.VirtualScreen.Width
                    x = SystemInformation.VirtualScreen.Width

                Case Else
                    x = MouseStruct.pt.X

            End Select

            ' Fix Y coordinate.
            Select Case MouseStruct.pt.Y

                Case Is > SystemInformation.VirtualScreen.Height
                    y = SystemInformation.VirtualScreen.Height

                Case Is < 0I
                    y = 0I

                Case Else
                    y = MouseStruct.pt.Y

            End Select

            Select Case wParam

                Case MouseMessages.WM_MOUSEMOVE
                    RaiseEvent MouseMove(Me, New Point(x, y))

                Case MouseMessages.WM_LBUTTONDOWN
                    RaiseEvent MouseLeftDown(Me, New Point(x, y))

                Case MouseMessages.WM_LBUTTONUP
                    If LeftClickTime <> 0 Then
                        LeftClickTime = Environment.TickCount() - LeftClickTime
                    End If

                    If (LeftClickTime <> 0) AndAlso (LeftClickTime < NativeMethods.GetDoubleClickTime()) Then
                        LeftClickTime = 0
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseLeftUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseLeftDoubleClick(Me, New Point(x, y))

                    Else
                        LeftClickTime = Environment.TickCount()
                        RaiseEvent MouseLeftUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_RBUTTONDOWN
                    RaiseEvent MouseRightDown(Me, New Point(x, y))

                Case MouseMessages.WM_RBUTTONUP
                    If RightClickTime <> 0 Then
                        RightClickTime = Environment.TickCount() - RightClickTime
                    End If

                    If (RightClickTime <> 0) AndAlso (RightClickTime < NativeMethods.GetDoubleClickTime()) Then
                        RightClickTime = 0
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseRightUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseRightDoubleClick(Me, New Point(x, y))

                    Else
                        RightClickTime = Environment.TickCount()
                        RaiseEvent MouseRightUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_MBUTTONDOWN
                    RaiseEvent MouseMiddleDown(Me, New Point(x, y))

                Case MouseMessages.WM_MBUTTONUP
                    If MiddleClickTime <> 0 Then
                        MiddleClickTime = Environment.TickCount() - MiddleClickTime
                    End If

                    If (MiddleClickTime <> 0) AndAlso (MiddleClickTime < NativeMethods.GetDoubleClickTime()) Then
                        MiddleClickTime = 0
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseMiddleUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseMiddleDoubleClick(Me, New Point(x, y))

                    Else
                        MiddleClickTime = Environment.TickCount()
                        RaiseEvent MouseMiddleUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_MOUSEWHEEL
                    RaiseEvent MouseWheel(Me, New Point(x, y), If(MouseStruct.mouseData < 0,
                                                                 WheelDirection.WheelDown,
                                                                 WheelDirection.WheelUp))

                Case Else
                    Exit Select ' Do Nothing

            End Select

            Return 0

        ElseIf nCode < 0I Then
            Return NativeMethods.CallNextHookEx(MouseHook, nCode, wParam, lParam)

        Else ' nCode > 0
            Return -1I

        End If

    End Function

#End Region

#Region " Hidden Methods "

    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetHashCode()
    End Sub

    ''' <summary>
    ''' Gets the System.Type of the current instance.
    ''' </summary>
    ''' <returns>The exact runtime type of the current instance.</returns>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function [GetType]()
        Return Me.GetType
    End Function

    ''' <summary>
    ''' Determines whether the specified System.Object instances are considered equal.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    ''' <summary>
    ''' Determines whether the specified System.Object instances are the same instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Private Shadows Sub ReferenceEquals()
    End Sub

    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ToString()
    End Sub

#End Region

#Region "IDisposable Support"

    ''' <summary>
    ''' Flag to detect redundant calls at <see cref="Dispose"/> method.
    ''' </summary>
    Private disposedValue As Boolean

    ''' <summary>
    ''' Releases unmanaged and optionally managed resources.
    ''' </summary>
    ''' <param name="disposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal disposing As Boolean)

        If Not Me.disposedValue Then

            If disposing Then ' Dispose managed state (managed objects).

            Else ' Free unmanaged resources (unmanaged objects).
                NativeMethods.UnhookWindowsHookEx(Me.MouseHook)

            End If

        End If

        Me.disposedValue = True

    End Sub

    ''' <summary>
    ''' Allows an object to try to free resources
    ''' and perform other cleanup operations before it is reclaimed by garbage collection.
    ''' </summary>
    Protected Overrides Sub Finalize()

        ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

        Me.Dispose(disposing:=False)
        MyBase.Finalize()

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Private Sub Dispose() Implements IDisposable.Dispose

        ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

        Me.Dispose(disposing:=True)
        GC.SuppressFinalize(obj:=Me)

    End Sub

#End Region

End Class

#End Region








Eleкtro

Otro repaso más a la Class, he añadido una funcionalidad experimental para restringir los eventos que envia la instancia del hook a los límites de un Rectangle (el Rectangle de la pantalla especificada, por ejemplo), lo he testeado en una pantalla normal, así como en Dual-Screen e invirtiendo el orden de la pantalla principal, todo parece haber ido sin irregularidades :).

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author           : Elektro
' Last Modified On : 09-26-2014
' ***********************************************************************
' <copyright file="MouseHook.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Instructions "

' Go to page:
' Project > Properties > Debug
'
' Then uncheck the option:
' "Enable the Visual Studio Hosting Process"

#End Region

#Region " Usage Examples "

#End Region

#Region " Imports "

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.InteropServices

#End Region

#Region " MouseHook "

''' <summary>
''' A low level mouse hook that processes mouse input events.
''' </summary>
Friend NotInheritable Class MouseHook : Implements IDisposable

#Region " P/Invoke "

    ''' <summary>
    ''' Platform Invocation methods (P/Invoke), access unmanaged code.
    ''' This class does not suppress stack walks for unmanaged code permission.
    ''' <see cref="System.Security.SuppressUnmanagedCodeSecurityAttribute"/>  must not be applied to this class.
    ''' This class is for methods that can be used anywhere because a stack walk will be performed.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/ms182161.aspx
    ''' </summary>
    Protected NotInheritable Class NativeMethods

#Region " Methods "

        ''' <summary>
        ''' Passes the hook information to the next hook procedure in the current hook chain.
        ''' A hook procedure can call this function either before or after processing the hook information.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644974%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' This parameter is ignored.
        ''' </param>
        ''' <param name="nCode">
        ''' The hook code passed to the current hook procedure.
        ''' The next hook procedure uses this code to determine how to process the hook information.
        ''' </param>
        ''' <param name="wParam">
        ''' The wParam value passed to the current hook procedure.
        ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
        ''' </param>
        ''' <param name="lParam">
        ''' The lParam value passed to the current hook procedure.
        ''' The meaning of this parameter depends on the type of hook associated with the current hook chain.
        ''' </param>
        ''' <returns>
        ''' This value is returned by the next hook procedure in the chain.
        ''' The current hook procedure must also return this value.
        ''' The meaning of the return value depends on the hook type.
        ''' For more information, see the descriptions of the individual hook procedures.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function CallNextHookEx(
               ByVal idHook As IntPtr,
               ByVal nCode As Integer,
               ByVal wParam As IntPtr,
               ByVal lParam As IntPtr
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Installs an application-defined hook procedure into a hook chain.
        ''' You would install a hook procedure to monitor the system for certain types of events.
        ''' These events are associated either with a specific thread
        ''' or with all threads in the same desktop as the calling thread.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' The type of hook procedure to be installed.
        ''' </param>
        ''' <param name="lpfn">
        ''' A pointer to the hook procedure.
        ''' If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process,
        ''' the lpfn parameter must point to a hook procedure in a DLL.
        ''' Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
        ''' </param>
        ''' <param name="hInstance">
        ''' A handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
        ''' The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
        ''' the current process and if the hook procedure is within the code associated with the current process.
        ''' </param>
        ''' <param name="threadId">
        ''' The identifier of the thread with which the hook procedure is to be associated.
        ''' For desktop apps, if this parameter is zero, the hook procedure is associated
        ''' with all existing threads running in the same desktop as the calling thread.
        ''' </param>
        ''' <returns>
        ''' If the function succeeds, the return value is the handle to the hook procedure.
        ''' If the function fails, the return value is NULL.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function SetWindowsHookEx(
               ByVal idHook As HookType,
               ByVal lpfn As LowLevelMouseProcDelegate,
               ByVal hInstance As IntPtr,
               ByVal threadId As UInteger
        ) As IntPtr
        End Function

        ''' <summary>
        ''' Removes a hook procedure installed in a hook chain by the 'SetWindowsHookEx' function.
        ''' For more info see here:
        ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ms644993%28v=vs.85%29.aspx
        ''' </summary>
        ''' <param name="idHook">
        ''' A handle to the hook to be removed.
        ''' This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
        ''' </param>
        ''' <returns>
        ''' If the function succeeds, the return value is nonzero.
        ''' If the function fails, the return value is zero.
        ''' </returns>
        <DllImport("user32.dll", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Auto)>
        Friend Shared Function UnhookWindowsHookEx(
               ByVal idHook As IntPtr
        ) As Boolean
        End Function

        ''' <summary>
        ''' Retrieves the current double-click time for the mouse.
        ''' A double-click is a series of two clicks of the mouse button,
        ''' the second occurring within a specified time after the first.
        ''' The double-click time is the maximum number of milliseconds that may occur
        ''' between the first and second click of a double-click.
        ''' The maximum double-click time is 5000 milliseconds.
        ''' </summary>
        ''' <returns>
        ''' The return value specifies the current double-click time, in milliseconds.
        ''' The maximum return value is 5000 milliseconds.
        ''' </returns>
        <DllImport("user32.dll", CharSet:=CharSet.Auto)>
        Friend Shared Function GetDoubleClickTime() As Integer
        End Function

#End Region

#Region " Enumerations "

        ''' <summary>
        ''' Indicates a type of Hook procedure to be installed.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644990%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Enum used in 'idHook' parameter of 'SetWindowsHookEx' function.")>
        Friend Enum HookType As UInteger

            ' **************************************
            ' This enumeration is partially defined.
            ' **************************************

            ''' <summary>
            ''' Installs a hook procedure that monitors low-level mouse input events.
            ''' For more information, see the LowLevelMouseProc hook procedure.
            ''' </summary>
            WH_MOUSE_LL = 14UI

        End Enum

        ''' <summary>
        ''' The event-injected flags.
        ''' An application can use the following values to test the flags.
        ''' Testing LLMHF_INJECTED (bit 0) will tell you whether the event was injected.
        ''' If it was, then testing LLMHF_LOWER_IL_INJECTED (bit 1) will tell you
        ''' whether or not the event was injected from a process running at lower integrity level.
        ''' </summary>
        <Flags()>
        <Description("Enum used in 'flags' parameter of 'MSLLHOOKSTRUCT' structure.")>
        Public Enum MSLLHOOKSTRUCTFlags As Integer

            ''' <summary>
            ''' Test the event-injected (from any process) flag.
            ''' </summary>
            LLMHF_INJECTED = 1I

            ''' <summary>
            ''' Test the event-injected (from a process running at lower integrity level) flag.
            ''' </summary>
            LLMHF_LOWER_IL_INJECTED = 2I

        End Enum

#End Region

#Region " Structures "

        ''' <summary>
        ''' The POINT structure defines the x- and y- coordinates of a point.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Structure used in 'pt' parameter of 'MSLLHOOKSTRUCT' structure.")>
        <StructLayout(LayoutKind.Sequential)>
        Friend Structure POINT

            ''' <summary>
            ''' The x-coordinate of the point.
            ''' </summary>
            Friend X As Integer

            ''' <summary>
            ''' The y-coordinate of the point.
            ''' </summary>
            Friend Y As Integer

        End Structure

        ''' <summary>
        ''' Contains information about a low-level mouse input event.
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644970%28v=vs.85%29.aspx
        ''' </summary>
        <Description("Structure used in 'lParam' parameter of 'CallNextHookEx' function.")>
        Friend Structure MSLLHOOKSTRUCT

            ''' <summary>
            ''' The ptThe x- and y-coordinates of the cursor, in screen coordinates.
            ''' </summary>
            Friend pt As NativeMethods.POINT

            ''' <summary>
            ''' If the message is 'WM_MOUSEWHEEL', the high-order word of this member is the wheel delta.
            ''' The low-order word is reserved.
            ''' A positive value indicates that the wheel was rotated forward, away from the user;
            ''' a negative value indicates that the wheel was rotated backward, toward the user.
            ''' One wheel click is defined as 'WHEEL_DELTA', which is '120'.
            ''' </summary>
            Friend mouseData As Integer

            ''' <summary>
            ''' The event-injected flag.
            ''' </summary>
            Friend flags As MSLLHOOKSTRUCTFlags

            ''' <summary>
            ''' The time stamp for this message.
            ''' </summary>
            Friend time As UInteger

            ''' <summary>
            ''' Additional information associated with the message.
            ''' </summary>
            Friend dwExtraInfo As IntPtr

        End Structure

#End Region

#Region " Delegates "

        ''' <summary>
        ''' Delegate LowLevelMouseProc
        ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
        ''' </summary>
        ''' <returns>
        ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
        ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
        ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
        ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
        ''' and may behave incorrectly as a result.
        ''' If the hook procedure processed the message,
        ''' it may return a nonzero value to prevent the system from passing the message to the rest of the hook chain or the target window procedure.
        ''' </returns>
        Friend Delegate Function LowLevelMouseProcDelegate(
                ByVal nCode As IntPtr,
                ByVal wParam As IntPtr,
                ByVal lParam As IntPtr
        ) As Integer

#End Region

#Region " Hidden Methods "

        ''' <summary>
        ''' Determines whether the specified System.Object instances are considered equal.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Public Shadows Sub Equals()
        End Sub

        ''' <summary>
        ''' Determines whether the specified System.Object instances are the same instance.
        ''' </summary>
        <EditorBrowsable(EditorBrowsableState.Never)>
        Private Shadows Sub ReferenceEquals()
        End Sub

#End Region

    End Class

#End Region

#Region " Objects "

    ''' <summary>
    ''' Handle to the hook procedure.
    ''' </summary>
    Private MouseHook As IntPtr

    ''' <summary>
    ''' The mouse hook delegate.
    ''' </summary>
    Private MouseHookDelegate As NativeMethods.LowLevelMouseProcDelegate

#End Region

#Region " Properties "

    ''' <summary>
    ''' ** ONLY FOR TESTING PURPOSES **
    ''' Gets or sets a value indicating whether to suppress the last MouseUp event of
    ''' the specified clicked button when a double-click fires.
    '''
    ''' If this value is set to <c>true</c>, the application will send the events in this order for a Double-Click:
    ''' MouseDown, MouseUp, MouseDown, MouseDoubleClick
    '''
    ''' If this value is set to <c>false</c>, the application will send the events in this order for a Double-Click:
    ''' MouseDown, MouseUp, MouseDown, MouseUp, MouseDoubleClick
    '''
    ''' </summary>
    ''' <value><c>true</c> if MouseUp event is suppressed; otherwise <c>false</c>.</value>
    Friend Property SuppressMouseUpEventWhenDoubleClick As Boolean = False

    ''' <summary>
    ''' ** ONLY FOR TESTING PURPOSES **
    ''' Gets or sets the screen's working area.
    ''' The events fired by <see cref="MouseHook"/> are restricted to the bounds of the specified rectangle.
    ''' </summary>
    ''' <value>The screen's working area.</value>
    Friend Property WorkingArea As Rectangle
        Get
            Return Me._Workingarea
        End Get
        Set(ByVal value As Rectangle)
            Me._Workingarea = value
        End Set
    End Property

    ''' <summary>
    ''' The screen's working area
    ''' </summary>
    Private _Workingarea As Rectangle = SystemInformation.VirtualScreen

#End Region

#Region " Enumerations "

    ''' <summary>
    ''' Indicates a Windows Message related to a mouse events.
    ''' For more info see here:
    ''' http://msdn.microsoft.com/en-us/library/windows/desktop/ff468877%28v=vs.85%29.aspx
    ''' </summary>
    Private Enum MouseMessages As UInteger

        ''' <summary>
        ''' Posted to a window when the cursor moves.
        ''' If the mouse is not captured, the message is posted to the window that contains the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MOUSEMOVE = &H200UI

        ''' <summary>
        ''' Posted when the user presses the left mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONDOWN = &H201UI

        ''' <summary>
        ''' Posted when the user releases the left mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_LBUTTONUP = &H202UI

        ''' <summary>
        ''' Posted when the user presses the right mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONDOWN = &H204UI

        ''' <summary>
        ''' Posted when the user releases the right mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_RBUTTONUP = &H205UI

        ''' <summary>
        ''' Posted when the user presses the middle mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONDOWN = &H207UI

        ''' <summary>
        ''' Posted when the user releases the middle mouse button while the cursor is in the client area of a window.
        ''' If the mouse is not captured, the message is posted to the window beneath the cursor.
        ''' Otherwise, the message is posted to the window that has captured the mouse
        ''' </summary>
        WM_MBUTTONUP = &H208UI

        ''' <summary>
        ''' Sent to the active window when the mouse's horizontal scroll wheel is tilted or rotated.
        ''' The DefWindowProc function propagates the message to the window's parent.
        ''' There should be no internal forwarding of the message,
        ''' since DefWindowProc propagates it up the parent chain until it finds a window that processes it.
        ''' </summary>
        WM_MOUSEWHEEL = &H20AUI

    End Enum

    ''' <summary>
    ''' Indicates the whell direction of the mouse.
    ''' </summary>
    Public Enum WheelDirection As Integer

        ''' <summary>
        ''' The wheel is moved up.
        ''' </summary>
        WheelUp = 1I

        ''' <summary>
        ''' The wheel is moved down.
        ''' </summary>
        WheelDown = 2I

    End Enum

#End Region

#Region " Events "

    ''' <summary>
    ''' Occurs when the mouse moves.
    ''' </summary>
    Friend Event MouseMove(ByVal sender As Object,
                           ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is pressed.
    ''' </summary>
    Friend Event MouseLeftDown(ByVal sender As Object,
                               ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button is released.
    ''' </summary>
    Friend Event MouseLeftUp(ByVal sender As Object,
                             ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse left button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseLeftDoubleClick(ByVal sender As Object,
                                      ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is pressed.
    ''' </summary>
    Friend Event MouseRightDown(ByVal sender As Object,
                                ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button is released.
    ''' </summary>
    Friend Event MouseRightUp(ByVal sender As Object,
                              ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse right button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseRightDoubleClick(ByVal sender As Object,
                                       ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is pressed.
    ''' </summary>
    Friend Event MouseMiddleDown(ByVal sender As Object,
                                 ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button is released.
    ''' </summary>
    Friend Event MouseMiddleUp(ByVal sender As Object,
                               ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse middle button performs a double-click.
    ''' A double click is considered as: (MouseLeftDown + MouseLeftUp) * 2
    ''' </summary>
    Friend Event MouseMiddleDoubleClick(ByVal sender As Object,
                                        ByVal MouseLocation As Point)

    ''' <summary>
    ''' Occurs when the mouse wheel is moved up or down.
    ''' </summary>
    Friend Event MouseWheel(ByVal sender As Object,
                            ByVal MouseLocation As Point,
                            ByVal WheelDirection As WheelDirection)

#End Region

#Region " Constructors "

    ''' <summary>
    ''' Prevents a default instance of the <see cref="MouseHook"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="MouseHook"/> class.
    ''' </summary>
    ''' <param name="Install">
    ''' If set to <c>true</c>, the Hook starts initialized for this <see cref="MouseHook"/> instance.
    ''' </param>
    Friend Sub New(Optional ByVal Install As Boolean = False)

        If Install Then
            Me.Install()
        End If

    End Sub

#End Region

#Region " Public Methods "

    ''' <summary>
    ''' Installs the Mouse Hook, then start processing messages to fire events.
    ''' </summary>
    Friend Sub Install()

        Me.MouseHookDelegate = New NativeMethods.LowLevelMouseProcDelegate(AddressOf LowLevelMouseProc)

        Try
            Me.MouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.HookType.WH_MOUSE_LL,
                                                          Me.MouseHookDelegate,
                                                          Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly.GetModules()(0)).ToInt32, 0)

        Catch ex As Exception
            Throw

        End Try

    End Sub

    ''' <summary>
    ''' Uninstalls the Mouse Hook and free all resources, then stop processing messages to fire events.
    ''' </summary>
    Friend Sub Uninstall()

        Me.Finalize()

    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Processes the mouse windows messages and raises it's corresponding events.
    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644986%28v=vs.85%29.aspx
    ''' </summary>
    ''' <param name="nCode">
    ''' A code the hook procedure uses to determine how to process the message.
    ''' If nCode is less than zero, the hook procedure must pass the message to the CallNextHookEx function
    ''' without further processing and should return the value returned by CallNextHookEx.
    ''' </param>
    ''' <param name="wParam">The identifier of the mouse message.</param>
    ''' <param name="lParam"> A pointer to an <see cref="NativeMethods.MSLLHOOKSTRUCT"/> structure.</param>
    ''' <returns>
    ''' If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
    ''' If nCode is greater than or equal to zero, and the hook procedure did not process the message,
    ''' it is highly recommended that you call CallNextHookEx and return the value it returns;
    ''' otherwise, other applications that have installed WH_MOUSE_LL hooks will not receive hook notifications
    ''' and may behave incorrectly as a result.
    ''' If the hook procedure processed the message,
    ''' it may return a nonzero value to prevent the system from passing the
    ''' message to the rest of the hook chain or the target window procedure.
    ''' </returns>
    Private Function LowLevelMouseProc(ByVal nCode As Integer,
                                       ByVal wParam As MouseMessages,
                                       ByVal lParam As IntPtr) As Integer

        Static LeftClickTime As Integer = 0I ' Determines a left button double-click.
        Static RightClickTime As Integer = 0I ' Determines a right button double-click.
        Static MiddleClickTime As Integer = 0I ' Determines a middle button double-click.

        If nCode = 0I Then

            Dim x As Integer
            Dim y As Integer

            Dim MouseStruct As NativeMethods.MSLLHOOKSTRUCT
            MouseStruct = CType(Marshal.PtrToStructure(lParam, MouseStruct.GetType()),
                                NativeMethods.MSLLHOOKSTRUCT)

            ' Fix X coordinate.
            Select Case MouseStruct.pt.X

                Case Is <= 0I
                    If MouseStruct.pt.X >= Me.WorkingArea.Location.X Then
                        x = MouseStruct.pt.X

                    ElseIf MouseStruct.pt.X <= Me.WorkingArea.Location.X Then

                        If MouseStruct.pt.X <= (Me.WorkingArea.Location.X - Me.WorkingArea.Width) Then
                            x = (Me.WorkingArea.Location.X - Me.WorkingArea.Width)
                        Else
                            x = MouseStruct.pt.X
                        End If

                    End If

                Case Is >= Me.WorkingArea.Width
                    x = Me.WorkingArea.Width

                Case Else
                    x = MouseStruct.pt.X

            End Select

            ' Fix Y coordinate.
            Select Case MouseStruct.pt.Y

                Case Is >= Me.WorkingArea.Height
                    y = Me.WorkingArea.Height

                Case Is <= 0I
                    y = 0I

                Case Else
                    y = MouseStruct.pt.Y

            End Select

            If x <= Me.WorkingArea.Width _
            AndAlso y < Me.WorkingArea.Height _
            AndAlso MouseStruct.pt.X > Me.WorkingArea.Width Then

                Return 0

            ElseIf x <= Me.WorkingArea.Width _
            AndAlso y < Me.WorkingArea.Height _
            AndAlso MouseStruct.pt.X < Me.WorkingArea.X Then

                Return 0

            ElseIf x = Me.WorkingArea.Width _
            AndAlso y < Me.WorkingArea.Height Then

                If Not Me.WorkingArea.Contains(x - 1, y) Then
                    Return 0
                End If

            ElseIf x < Me.WorkingArea.Width _
            AndAlso y = Me.WorkingArea.Height Then

                If Not Me.WorkingArea.Contains(x, y - 1) Then
                    Return 0
                End If

            End If

            Select Case wParam

                Case MouseMessages.WM_MOUSEMOVE
                    RaiseEvent MouseMove(Me, New Point(x, y))

                Case MouseMessages.WM_LBUTTONDOWN
                    RaiseEvent MouseLeftDown(Me, New Point(x, y))

                Case MouseMessages.WM_LBUTTONUP
                    If LeftClickTime <> 0 Then
                        LeftClickTime = Environment.TickCount() - LeftClickTime
                    End If

                    If (LeftClickTime <> 0I) AndAlso (LeftClickTime < NativeMethods.GetDoubleClickTime()) Then
                        LeftClickTime = 0I
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseLeftUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseLeftDoubleClick(Me, New Point(x, y))

                    Else
                        LeftClickTime = Environment.TickCount()
                        RaiseEvent MouseLeftUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_RBUTTONDOWN
                    RaiseEvent MouseRightDown(Me, New Point(x, y))

                Case MouseMessages.WM_RBUTTONUP
                    If RightClickTime <> 0I Then
                        RightClickTime = Environment.TickCount() - RightClickTime
                    End If

                    If (RightClickTime <> 0I) AndAlso (RightClickTime < NativeMethods.GetDoubleClickTime()) Then
                        RightClickTime = 0I
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseRightUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseRightDoubleClick(Me, New Point(x, y))

                    Else
                        RightClickTime = Environment.TickCount()
                        RaiseEvent MouseRightUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_MBUTTONDOWN
                    RaiseEvent MouseMiddleDown(Me, New Point(x, y))

                Case MouseMessages.WM_MBUTTONUP
                    If MiddleClickTime <> 0I Then
                        MiddleClickTime = Environment.TickCount() - MiddleClickTime
                    End If

                    If (MiddleClickTime <> 0I) AndAlso (MiddleClickTime < NativeMethods.GetDoubleClickTime()) Then
                        MiddleClickTime = 0I
                        If Not Me.SuppressMouseUpEventWhenDoubleClick Then
                            RaiseEvent MouseMiddleUp(Me, New Point(x, y))
                        End If
                        RaiseEvent MouseMiddleDoubleClick(Me, New Point(x, y))

                    Else
                        MiddleClickTime = Environment.TickCount()
                        RaiseEvent MouseMiddleUp(Me, New Point(x, y))

                    End If

                Case MouseMessages.WM_MOUSEWHEEL
                    RaiseEvent MouseWheel(Me, New Point(x, y), If(MouseStruct.mouseData < 0I,
                                                                 WheelDirection.WheelDown,
                                                                 WheelDirection.WheelUp))

                Case Else
                    Exit Select ' Do Nothing

            End Select

            Return 0I

        ElseIf nCode < 0I Then
                Return NativeMethods.CallNextHookEx(MouseHook, nCode, wParam, lParam)

        Else ' nCode > 0
                Return -1I

        End If

    End Function

#End Region

#Region " Hidden Methods "

    ''' <summary>
    ''' Serves as a hash function for a particular type.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub GetHashCode()
    End Sub

    ''' <summary>
    ''' Gets the System.Type of the current instance.
    ''' </summary>
    ''' <returns>The exact runtime type of the current instance.</returns>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Function [GetType]()
        Return Me.GetType
    End Function

    ''' <summary>
    ''' Determines whether the specified System.Object instances are considered equal.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub Equals()
    End Sub

    ''' <summary>
    ''' Determines whether the specified System.Object instances are the same instance.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Private Shadows Sub ReferenceEquals()
    End Sub

    ''' <summary>
    ''' Returns a String that represents the current object.
    ''' </summary>
    <EditorBrowsable(EditorBrowsableState.Never)>
    Public Shadows Sub ToString()
    End Sub

#End Region

#Region "IDisposable Support"

    ''' <summary>
    ''' Flag to detect redundant calls at <see cref="Dispose"/> method.
    ''' </summary>
    Private disposedValue As Boolean

    ''' <summary>
    ''' Releases unmanaged and optionally managed resources.
    ''' </summary>
    ''' <param name="disposing">
    ''' <c>true</c> to release both managed and unmanaged resources;
    ''' <c>false</c> to release only unmanaged resources.
    ''' </param>
    Protected Sub Dispose(ByVal disposing As Boolean)

        If Not Me.disposedValue Then

            If disposing Then ' Dispose managed state (managed objects).

            Else ' Free unmanaged resources (unmanaged objects).
                NativeMethods.UnhookWindowsHookEx(Me.MouseHook)

            End If

        End If

        Me.disposedValue = True

    End Sub

    ''' <summary>
    ''' Allows an object to try to free resources
    ''' and perform other cleanup operations before it is reclaimed by garbage collection.
    ''' </summary>
    Protected Overrides Sub Finalize()

        ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

        Me.Dispose(disposing:=False)
        MyBase.Finalize()

    End Sub

    ''' <summary>
    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    ''' </summary>
    Private Sub Dispose() Implements IDisposable.Dispose

        ' Do not change this code. Put cleanup code in method: Dispose(ByVal disposing As Boolean)

        Me.Dispose(disposing:=True)
        GC.SuppressFinalize(obj:=Me)

    End Sub

#End Region

End Class

#End Region