【问题标题】:How do I set the tabIndex for a Button at run time in WinForms?如何在 WinForms 中运行时为按钮设置 tabIndex?
【发布时间】:2015-08-30 10:31:52
【问题描述】:

我有一个通用消息框,我们有几个面板,我们在运行时在其中添加控件。

在我的表单中,我已经在 pnlBottom 上添加了 pnlButtons 以及其他一些控件。

现在在运行时,我正在向pnlButtons 添加一个OK 按钮,该按钮位于pnlBottom 上。我没有为Designer.vb 文件中的任何控件设置TabIndex

我正在尝试使用下面的代码将注意力集中在OK 按钮上,但它不起作用。

For Each control As Control In Me.Controls
    If TypeOf (control) Is Panel Then
        Dim pnlBottons As Panel = CType(control, Panel)
        If pnlBottons.Name = "pnlBottom" Then
            For Each ctrl As Control In control.Controls
                Dim pnlButtons As Panel = CType(ctrl, Panel)
                If pnlButtons.Name = "pnlButtons" Then
                    For Each ctrlbtn As Control In ctrl.Controls
                        If TypeOf (ctrlbtn) Is Button Then
                            Dim textBox As Button = CType(ctrlbtn, Button)
                            textBox.Parent.Parent.TabIndex = 0
                            textBox.Parent.TabIndex = 0
                            textBox.TabIndex = 0
                        End If
                    Next
                End If
            Next
        End If
    End If
Next

在这里,我将 pnlBottompnlButtonsOK 按钮的 TabIndex 设置为 0。

请建议如何聚焦OK 按钮。

【问题讨论】:

  • If textBox.Text = "OK" Then textBox.Focus()? (没有那些 Parent 和 TabIndex)
  • 这不是 TabIndex 应该如何工作的。 TabIndex 确定通过 tab 键访问控件的顺序(从最低到最高索引,没有特定的第一个/最后一个索引)。要在运行时将焦点设置在特定控件上,您可以依赖 Focus() 方法,如上一条评论中所建议的那样。
  • 我为 StackOverflow 制作了一个小工具,可以轻松将代码缩进增加或减少 4 个空格Here's the link 使用它。
  • textBox.Focus() 没有在运行时将焦点设置在我的按钮控件上。所以我认为我可以使用标签索引 o(zero) 来显示 OK 按钮上的焦点,但它不起作用。
  • 哪个控件有焦点?

标签: vb.net winforms


【解决方案1】:

您可以使用以下方式之一set the focus on a control during Form Load event

1- Control.Select 方法

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
    Me.OKButton.Select()
End Sub

Focus 是一种低级方法,主要用于自定义控件 作者。相反,应用程序程序员应该使用 Select 方法 或子控件的 ActiveControl 属性,或激活 表单的方法。


2- Form.ActiveControl 属性

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
    Me.ActiveControl = Me.OKButton
End Sub

3- Control.Focus 方法

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
    Me.Show()
    Me.OKButton.Focus()
End Sub

我们调用 Me.Show() 的原因是将表单设置为 true。根据:

您可以在表单的 Load 事件中使用 Control.Focus 方法来 仅在窗体的 Visible 属性之后将焦点设置在控件上 设置为 True。


如果你不能使用Me.OKButton,你可以像这样找到你想要的控件:

Dim control = Me.Controls.Find("OKButton", True).FirstOrDefault()
If Not control Is Nothing Then
    control.Select() 'or other stuff
End If

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多