You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中UserControl窗体条码文本框默认聚焦选中问题

问题:VB.NET UserControl中首次加载时文本框无法聚焦选中

我想在VB.NET的UserControl窗体中实现条码文本框加载时默认聚焦并选中内容,不想使用Form_Load,仅在Public Sub New中编写了如下代码,但首次加载窗体时文本框未处于选中状态,请问我的代码是否存在问题?

Namespace project.Pages

    Partial Public Class PgItemTransfer
        Inherits UserControl

        Public Sub New()

            If Program.IsInDesignMode(Me) Then
                Return
            End If

            InitializeComponent()

            ColAvatar.FillWeight = 30.0!
            ColAvatar.Width = 30
            ColEdit.FillWeight = 30.0!
            ColEdit.Width = 46

            LoadData()
            
            BtxtBarcode.Focus()
            BtxtBarcode.Select()
            
        End Sub

问题原因及解决方案

  • 核心问题是控件生命周期时机错误:在Public Sub New构造函数中调用Focus()和Select()时,UserControl尚未完全嵌入父窗体的控件树,文本框此时不具备获取焦点的条件,调用不会生效。
  • 正确做法是在UserControl自身的Load事件(或重写OnLoad方法)中执行焦点设置,此时控件已完成加载并具备交互能力:

修改方案1:绑定Load事件

Namespace project.Pages

    Partial Public Class PgItemTransfer
        Inherits UserControl

        Public Sub New()
            If Program.IsInDesignMode(Me) Then
                Return
            End If

            InitializeComponent()

            ColAvatar.FillWeight = 30.0!
            ColAvatar.Width = 30
            ColEdit.FillWeight = 30.0!
            ColEdit.Width = 46

            LoadData()
            
            ' 绑定控件加载事件
            AddHandler Me.Load, AddressOf PgItemTransfer_Load
        End Sub

        Private Sub PgItemTransfer_Load(sender As Object, e As EventArgs)
            BtxtBarcode.Focus()
            BtxtBarcode.SelectAll() ' 使用SelectAll确保选中全部内容,比Select()更可靠
        End Sub
    End Class
End Namespace

修改方案2:重写OnLoad方法

Namespace project.Pages

    Partial Public Class PgItemTransfer
        Inherits UserControl

        Public Sub New()
            If Program.IsInDesignMode(Me) Then
                Return
            End If

            InitializeComponent()

            ColAvatar.FillWeight = 30.0!
            ColAvatar.Width = 30
            ColEdit.FillWeight = 30.0!
            ColEdit.Width = 46

            LoadData()
        End Sub

        Protected Overrides Sub OnLoad(e As EventArgs)
            MyBase.OnLoad(e)
            BtxtBarcode.Focus()
            BtxtBarcode.SelectAll()
        End Sub
    End Class
End Namespace

内容的提问来源于stack exchange,提问作者roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 19:03:21