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

如何在UserControl中利用KeyUp事件转移焦点?代码无效果求指导

问题原因及解决方法

你的代码无效主要是以下几个常见原因:

  • UserControl未开启按键预览:默认情况下,UserControl不会优先接收按键事件,按键会被当前有焦点的子控件拦截,导致PgItemTransfer_KeyUp事件根本没触发。
  • UserControl未获得焦点:如果UserControl本身没有焦点,它的按键事件不会被触发。
  • KeyUp事件时机问题:部分场景下KeyUp事件可能因为焦点变化被跳过,改用KeyDown事件更可靠。

修正后的代码(已补充中文说明)

Partial Public Class 商品转移页面 ' 原类名:PgItemTransfer
    Inherits UserControl
    Public Sub New()
        If Program.IsInDesignMode(Me) Then
            Return
        End If
        InitializeComponent()
        ' 开启按键预览,让UserControl优先接收按键事件
        Me.KeyPreview = True
        ' 设置允许UserControl获得焦点
        Me.TabStop = True
    End Sub

    ' 改用KeyDown事件,比KeyUp更稳定
    Private Sub 商品转移页面_按键按下(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Me.KeyDown ' 原方法名:PgItemTransfer_KeyDown
        Try
            Select Case e.KeyCode
                Case Keys.F8
                    ' 确保文本框可用且可见
                    If BtxtBarcode IsNot Nothing AndAlso BtxtBarcode.Enabled AndAlso BtxtBarcode.Visible Then
                        BtxtBarcode.Focus()
                        ' 标记事件已处理,避免后续控件继续响应
                        e.Handled = True
                    End If
            End Select
        Catch ex As Exception
            MessageBox.Show(ex.Message, "POS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try
    End Sub
End Class

额外检查项

  • 确认BtxtBarcode控件的Enabled和Visible属性都设为True,否则无法获得焦点。
  • 如果UserControl是被其他容器(比如Panel)包裹,确保容器没有拦截按键事件,或者也开启容器的KeyPreview。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:12:04