-1

Hi I'm implementing a custom menu in a panel like this image (link) below..

heres the link http://i.imgur.com/5OlRk9c.png

My question is, how can I detect that the user clicks on another part of my form excepts the menu panel and buttons(inside the red circle).

I already used the LostFocus event but nothing happens.

Please help.

1 Answers1

0

You can trap mouse messages before they get routed to the controls via IMessageFilter. Then you can check to see if the cursor position is inside or outside the bounds of your panel. Here's a simple example with Panel1:

Public Class Form1

    Private WithEvents filter As New MyFilter

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Application.AddMessageFilter(filter)
    End Sub

    Private Sub filter_LeftClick() Handles filter.LeftClick
        Dim rc As Rectangle = Panel1.RectangleToScreen(Panel1.ClientRectangle)
        If Not rc.Contains(Cursor.Position) Then
            Debug.Print("Click outside of Panel1")
        End If
    End Sub

    Private Class MyFilter
        Implements IMessageFilter

        Public Event LeftClick()
        Private Const WM_LBUTTONDOWN As Integer = &H201

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

            End Select
            Return False
        End Function

    End Class

End Class
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • how can stop this function from running? – Mike Bustos Aug 18 '15 at 07:39
  • Thanks, i already figure it out! i use exit sub if the panel is already not visible. Big thanks! can you give me another explanation for this solution so that i can confidently use it in future. THANKS! – Mike Bustos Aug 18 '15 at 07:44
  • Basically IMessageFilter allows you catch all messages that are intended for your application in one place. [IMessageFilter](https://msdn.microsoft.com/en-us/library/system.windows.forms.imessagefilter(v=vs.110).aspx) _A class that implements the IMessageFilter interface can be added to the application's message pump to filter out a message or perform other operations before the message is dispatched to a form or control._ – Idle_Mind Aug 19 '15 at 02:59