Question

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
Was it helpful?

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.

OTHER TIPS

I figured out how to do this myself - for anyone interested I am doing the following:

Private _parentForm As Form

Private Sub UserControl_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    _parentForm = CType(Parent, Form)
    AddHandler _parentForm.Click, AddressOf ParentForm_Click
End Sub

Private Sub ParentForm_Click(sender As Object, e As System.EventArgs)
    debug.writeline("Parent form clicked")
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top