GregH
GregH

Reputation: 12858

Handling a MouseDown Event Regardless Of The Control

Is it possible to handle a mouseDown event in VB.Net (2008) regardless of the control firing the mouseDown event? Basically, I just want to catch a mouseDown event at the "form level" and don't want to program mouseDown event handlers in every control. Is there a way to do this?

Upvotes: 0

Views: 3996

Answers (2)

Hans Passant
Hans Passant

Reputation: 941465

This is very unusual, you almost always really care what particular control was clicked. And have a MouseDown event that takes a specific action, based on the clicked control. But you can, you can catch input events before they are dispatched to the control itself. You need to use the IMessageFilter interface. Best explained with a code sample:

Public Class Form1
  Implements IMessageFilter

  Public Sub New()
    InitializeComponent()
    Application.AddMessageFilter(Me)
  End Sub

  Protected Overrides Sub OnFormClosed(ByVal e As System.Windows.Forms.FormClosedEventArgs)
    Application.RemoveMessageFilter(Me)
  End Sub

  Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
    REM catch WM_LBUTTONDOWN
    If m.Msg = &H201 Then
      Dim pos As New Point(m.LParam.ToInt32())
      Dim ctl As Control = Control.FromHandle(m.HWnd)
      If ctl IsNot Nothing Then
        REM do something...
      End If
      REM next line is optional
      Return False
    End If
  End Function
End Class

Beware that this filter is active for all forms in your app. You'll need to filter on the ctl value if you want to make it specific to only one form.

Upvotes: 4

dbasnett
dbasnett

Reputation: 11773

Private Sub Form1_Load(ByVal sender As System.Object, _
                       ByVal e As System.EventArgs) Handles MyBase.Load
    'note - this will NOT work for containers i.e. tabcontrols, etc
    For Each c In Me.Controls
        Try
            AddHandler DirectCast(c, Control).MouseDown, AddressOf Global_MouseDown
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try
    Next
End Sub

Private Sub Global_MouseDown(ByVal sender As Object, _
                              ByVal e As System.Windows.Forms.MouseEventArgs)
    Debug.WriteLine(DirectCast(sender, Control).Name)
End Sub

Upvotes: 1

Related Questions