无法将焦点设置在 Windows 窗体文本框上 [英] Can't set focus on a Windows Forms textbox

查看:31
本文介绍了无法将焦点设置在 Windows 窗体文本框上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当标签页第一次出现时,我似乎无法将输入焦点放在文本框上(我使用的是 Windows 窗体、VB.NET 3.5).

I can't seem to get input focus on a textbox when a tab page first comes up (I'm using Windows Forms, VB.NET 3.5).

我在标签页的面板上有一个文本框,当标签页出现时,我希望焦点位于文本框上.我希望用户能够立即在焦点文本框中开始输入,而无需单击文本框.我按照我想要的顺序设置了制表位,文本框是第一个制表位.该选项卡除了选项卡页面出现时,重点不会在TextBox上,即首先在选项卡顺序中的焦点.

I have a textbox on a panel on a tab page, and I want the focus to be on the textbox when the tab page comes up. I want the user to be able to start typing immediately in the focused textbox without having to click on the textbox. I have tab stops set in the order I want and the textbox is the first tab stop. The tab stops work except that when the tab page comes up the focus is not on the textbox, i.e. the one that's first in the tab order.

在标签页的Enter事件处理程序中我调用了文本框的Focus方法,但是它返回False并且什么都不做,没有错误信息.我知道我可以访问文本框,因为在代码的同一点我可以设置文本框的文本.

In the Enter event handler of the tab page I call the Focus method of the text box, but it returns False and does nothing, no error messages. I know I can access the text box because at the same point in the code I can set the text of the text box.

如果重要的话,标签页的布局有点复杂:

If it matters, the layout of the tab page is a little complicated:

frmFoo/TabControl1/TabPageX/Panel1/Panel2/TextBox1

我想将焦点设置在 TextBox1 上.

I want to set the focus on TextBox1.

  1. 将焦点放在所需文本框上的最佳方法是什么?
  2. 如果设置焦点是最好的方法,为什么 textbox.Focus() 方法失败?

推荐答案

我假设您正在尝试在表单加载事件处理程序中设置焦点?如果是这样,您需要在设置焦点之前执行 Me.Show() 以实际创建屏幕控件.类似的东西:

I would assume you are attempting to set focus in the form load event handler? If so, you need to do a Me.Show() to actually create the onscreen controls before focus can be set. Something along the lines of:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Me.Show()
    Application.DoEvents()
    TextBox1.Focus()
End Sub

如果您不执行 Me.Show(),则在加载事件完成之前不会显示表单.

If you don't do the Me.Show(), the form is NOT displayed until the load event is complete.

对于tab控件,处理_SelectedIndexChanged事件:

For the tab control, handle the _SelectedIndexChanged event:

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
  Handles TabControl1.SelectedIndexChanged

    If TabControl1.SelectedTab.Name = "TabPage1" Then
        TextBox2.Focus()
    End If
    If TabControl1.SelectedTab.Name = "TabPage2" Then
        TextBox4.Focus()
    End If

如果选择的第一个字段是选项卡控件上的文本框,您仍然希望在加载事件中设置初始焦点,如上所示.

You will still want to set the initial focus in the load event as shown above if the first field selected is to be the textbox on the tab control.

这篇关于无法将焦点设置在 Windows 窗体文本框上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆