views:

75

answers:

2

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?

+2  A: 

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() And &HFFFF, m.LParam.ToInt32() >> 16)
      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.

Hans Passant
The problem I'm facing is that I am using a custom developed control. It seems for some reason, the person that wrote it did not handle the mouseDown event because when I handle the mouseDown event for the control, the event never fires.
GregH
@GregH: that rings a bell. I already gave you a solution for that: http://stackoverflow.com/questions/2609325/are-vb-net-eventargs-maintained-at-a-system-level
Hans Passant
A: 
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
dbasnett