如何检查聚焦动态创建的控件?

时间:2015-10-20 17:49:34

标签: c# .net vb.net

在我的Windows窗体中,控件是动态创建的。那么现在,我可以在哪种形式事件中检查哪个控件具有焦点?

例如,我在表单加载时动态创建4个按钮,之后如果我点击一个按钮,其他3应该消失。表单上没有其他内容。

1 个答案:

答案 0 :(得分:1)

如果您能够处理它的点击事件,您不需要知道哪个控件具有焦点。为所有按钮创建一个处理程序。当动态创建按钮时,为它们添加处理程序。此代码可能会在您创建按钮的循环中进行。或者您可以明确地制作每一个。例如:

Dim newButton As New Button
AddHandler newButton.Click, AddressOf buttonClicked

这是处理程序:

Private Sub buttonClicked(sender As Object, e As EventArgs)
    'Handle the click event here.
    Dim clickedButton As Button = CType(sender, Button)
    For Each c As Control In Controls
        If TypeOf c Is Button Then
            If Not c.Equals(clickedButton) Then
                c.Visible = False
            End If
        End If
    Next
End Sub