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

C# .NET Framework下文本框KeyUp返回及PageUp/PageDown切换文本框的代码

问题解答

1. 是否存在文本框KeyUp事件触发返回操作的代码?

存在。可以通过在文本框的KeyUp事件中检测特定按键(比如ESC键)来触发返回操作,示例代码如下:

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    // 检测是否按下ESC键
    if (e.KeyCode == Keys.Escape)
    {
        // 执行返回操作,比如关闭当前窗口/回到上一页
        this.Close(); // 可根据需求替换为具体返回逻辑
    }
}

2. 在C# .NET Framework中,除了上下箭头键外,是否有实现PageUp和PageDown键导航至前一个和后一个文本框的代码?

有,以下是实现PageUp/PageDown键切换文本框的示例代码:

private void Control_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.PageUp || e.KeyCode == Keys.PageDown)
    {
        if (sender is TextBox currentTextBox)
        {
            // 获取当前文本框在父容器控件集合中的索引
            int currentIndex = currentTextBox.Parent.Controls.IndexOf(currentTextBox);

            // 根据按下的按键计算前一个或后一个文本框的索引
            int newIndex = e.KeyCode == Keys.PageUp ? currentIndex - 1 : currentIndex + 1;

            // 检查新索引是否在文本框的有效范围内
            if (newIndex >= 0 && newIndex < currentTextBox.Parent.Controls.Count)
            {
                TextBox newTextBox = (TextBox)currentTextBox.Parent.Controls[newIndex];

                // 将焦点设置到前一个或后一个文本框
                newTextBox.Focus();
            }
        }
    }
}

代码说明:

  • 监听控件的KeyUp事件,判断是否按下PageUp或PageDown键
  • 获取当前文本框在父容器中的索引,根据按键计算目标文本框的索引
  • 验证索引有效性后,将焦点切换到目标文本框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:52:41