Friday, February 6, 2009

Capture mouse click before control in VB.net

Copy the following code snippet your form. I got this code from the thread above and just added a public variable to store the control that the mouse is currently over.

Public Class Form2

Public myCtrlOver As String
Private WithEvents mf As New MyFilter

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.AddMessageFilter(mf)
End Sub

Private Sub mf_MouseMove() Handles mf.MouseMove
If Form.ActiveForm Is Me Then
Dim clientPT As Point
Dim formPT As Point = Me.PointToClient(Cursor.Position)
Dim ctlName As String
Dim ctl As Control = FindControl(Me)
If Not IsNothing(ctl) Then
ctlName
= ctl.Name
clientPT
= ctl.PointToClient(Cursor.Position)
Else
ctlName
= Me.Name
clientPT
= Me.PointToClient(Cursor.Position)
End If
' Debug.Print(ctlName & ": " & clientPT.ToString & " Form: " & formPT.ToString)

myCtrlOver = ctlName

Me.Label1.Text = ctlName
Me.Label1.Refresh()
Else
'
...WM_MOUSEMOVE is targeting a form other than this one...
End If
End Sub

Private Function FindControl(ByVal cont As Control) As Control
Dim ctl As Control = cont.GetChildAtPoint(cont.PointToClient(Cursor.Position))
If Not IsNothing(ctl) Then
If ctl.HasChildren Then
Dim subCtl As Control = FindControl(ctl)
If Not IsNothing(subCtl) Then
Return subCtl
Else
Return ctl
End If
Else
Return ctl
End If
Else
Return Nothing
End If
End Function

Private Class MyFilter
Implements IMessageFilter

Public Event MouseMove()
Private Const WM_MOUSEMOVE As Integer = &H200

Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
Select Case m.Msg
Case WM_MOUSEMOVE
RaiseEvent MouseMove()

End Select
End Function

End Class

Private Sub Form2_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

If myCtrlOver <> "YourMenuPanelName" Then

' Put your code here to close the menu

End If

End Sub
End Class

No comments:

Post a Comment