是否可以从用户控件中检测表单鼠标单击

时间:2012-01-12 09:52:24

标签: vb.net winforms user-controls mouseclick-event

我创建了一个用户控件,希望能够检测用户何时单击表单。

我看到this question是相关的但是使用Leave事件的建议并不总是按我的意愿行事,因为当用户点击表单时焦点不一定会改变(我的控件可能是Form上唯一的控件,在这种情况下,焦点保持在我的控件上。)

有什么想法吗?

我希望能够在用户控件中执行类似的操作:

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

End Sub

2 个答案:

答案 0 :(得分:3)

我的做法略有不同:

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

如果它不是表单的直接子节点,如果它的父节点改变了等,则会给它带来更多的弹性。

答案 1 :(得分:0)

我想出了自己如何做到这一点 - 对于任何有兴趣的人我都在做以下事情:

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