Search code examples
vb.netwinformsuser-controlsmouseclick-event

Is it possible to detect a Form mouseclick from a User Control


I have created a User Control and would like to be able to detect when the user clicks on the Form.

I have seen this question which is related but the suggestion to use the the Leave event doesn't always do what I want because the focus doesn't necessarily change when the user clicks the Form (my control could be the only control on the Form in which case focus stays with my control).

Any ideas?

I want to be able to do something like this from within the User Control:

Private Sub ParentForm_Click(sender As Object, e As System.EventArgs) _
    Handles Me.Parent.Click

End Sub

Solution

  • I would do it slightly differently:

    Private _form As Control
    
    Private Sub UserControl_ParentChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.ParentChanged
    
        If _form IsNot Nothing Then
            RemoveHandler _form.Click, AddressOf ParentOnClick
        End If
    
        _form = Me.FindForm()
    
        If _form IsNot Nothing Then
            AddHandler _form.Click, AddressOf ParentOnClick
        End If
    
    End Sub
    
    Private Sub ParentOnClick(ByVal sender As Object, ByVal e As EventArgs)
        '...
    End Sub
    

    This gives it a little more resillience - if it is not a direct child of a Form, if its parent changes etc.