As part of my work on flick scrolling I’ve created an example of a class that can create mouse events for an entire Winforms application.
To use it, just declare it, like so:
Private WithEvents moAppMouseEvents As New ApplicationLevelMouseEvent
I’ve only implemented the MouseUp and MouseDown events, but these are consistent with the Form ones:
Private Sub moAppMouseEvents_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles moAppMouseEvents.MouseUp
End Sub
Private Sub moAppMouseEvents_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles moAppMouseEvents.MouseDown
End Sub
The code uses an IMessageFilter in the tradtional fashion:
Public Class ApplicationLevelMouseEvents
Implements IDisposable
Implements IMessageFilter
Public Event MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Public Event MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
Private Const WM_LBUTTONUP As Integer = &H202
Private Const WM_LBUTTONDOWN As Integer = &H201
'Private Const WM_RBUTTONDOWN As Integer = &H204
'Private Const WM_MBUTTONDOWN As Integer = &H207
'Private Const WM_NCLBUTTONDOWN As Integer = &HA1
'Private Const WM_NCRBUTTONDOWN As Integer = &HA4
'Private Const WM_NCMBUTTONDOWN As Integer = &HA7
Public Sub New()
Application.AddMessageFilter(Me)
End Sub
Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
If (m.Msg = WM_LBUTTONDOWN) Then
Dim loArgs As New MouseEventArgs(MouseButtons.Left, 1, System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y, 0)
RaiseEvent MouseDown(Me, loArgs)
ElseIf (m.Msg = WM_LBUTTONUP) Then
Dim loArgs As New MouseEventArgs(MouseButtons.Left, 1, System.Windows.Forms.Cursor.Position.X, System.Windows.Forms.Cursor.Position.Y, 0)
RaiseEvent MouseUp(Me, loArgs)
End If
Debug.WriteLine(m.Msg.ToString)
Return False
End Function
Private disposedValue As Boolean = False ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
Application.RemoveMessageFilter(Me)
End If
End If
Me.disposedValue = True
End Sub
#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
The sample could be enhanced to support the full range of events such as mouse move, so feel free to take the sample and change it. If you post your code, please link back to this post.