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

Windows Forms应用中如何通过按键切换TextBox及按钮的选中焦点

解决方案

在WinForms中,要实现控件间的焦点切换,直接调用目标控件的Focus()方法就可以,这就是你想要的类似this.SelectedItem = TxtBoxName的实现方式。以下是修改后的完整代码:

private void TxtBoxName_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        if(TextIsEmpty(TxtBoxDebt.Text))
        {
            // 切换到TxtBoxDebt
            TxtBoxDebt.Focus();
        }
        else
        {
            AssignNewPerson();
        }
    }
    if (e.KeyCode == Keys.Down)
    {
        // 切换到TxtBoxDebt
        TxtBoxDebt.Focus();
    }
}
private void TxtBoxDebt_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        AssignNewPerson();
    }
    else if (e.KeyCode == Keys.Up)
    {
        // 切换到TxtBoxName
        TxtBoxName.Focus();
    }
    else if(e.KeyCode == Keys.Down)
    {
        // 切换到TxtBoxNote
        TxtBoxNote.Focus();
    }
}
private void TxtBoxNote_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        AssignNewPerson();
    }
    else if (e.KeyCode == Keys.Up)
    {
        // 切换到TxtBoxDebt
        TxtBoxDebt.Focus();
    }
    else if (e.KeyCode == Keys.Down)
    {
        // 切换到BtnAssign
        BtnAssign.Focus();
    }
}

额外优化建议

如果不想为每个控件单独写KeyDown事件,可以统一绑定一个公共事件处理方法,通过判断当前焦点控件来决定下一个焦点目标,减少重复代码。比如:

private void Common_KeyDown(object sender, KeyEventArgs e)
{
    Control currentControl = sender as Control;
    if (currentControl == null) return;

    switch (e.KeyCode)
    {
        case Keys.Enter:
            AssignNewPerson();
            break;
        case Keys.Up:
            if (currentControl == TxtBoxDebt)
                TxtBoxName.Focus();
            else if (currentControl == TxtBoxNote)
                TxtBoxDebt.Focus();
            break;
        case Keys.Down:
            if (currentControl == TxtBoxName)
                TxtBoxDebt.Focus();
            else if (currentControl == TxtBoxDebt)
                TxtBoxNote.Focus();
            else if (currentControl == TxtBoxNote)
                BtnAssign.Focus();
            break;
    }
}

之后只需要把所有TextBox和按钮的KeyDown事件绑定到这个Common_KeyDown方法即可。

内容的提问来源于stack exchange,提问作者semih yılmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:00:46