c# - 在 Control.GotFocus 中检测用户是否向前或向后导航?

标签 c# winforms focus

有了以下 WinForms 对话框表单,我正在处理 GotFocus MyControl 的事件:

enter image description here

MyControl 源自 DevExpress XtraUserControl它又源自 Microsoft WinForms 标准 UserControl .

我想要实现的是,当用户使用 Tab 导航时 MyControl 获得焦点并且 MyControl 获得焦点时,焦点被转发到子控件。

我使用以下代码成功完成了此操作:

protected override void OnGotFocus(EventArgs e)
{
    base.OnGotFocus(e);

    // Forward.
    foreach (Control control in Controls)
    {
        if (control.TabStop)
        {
            control.Select();
            break;
        }
    }
}

即如果按钮 1 获得焦点并且用户按下 Tab 键,焦点将设置为按钮 2

无法解决的是用户是否向后导航。 IE。如果 Button 4 获得焦点并且用户按下 Shift+Tab 键,则焦点应设置为 Button 3 >.

我的两个问题是:

  • 有没有办法在 GotFocus 事件中检测用户的导航顺序?
  • 我的做法完全正确吗?也许有一个内置函数/标志我可以设置为 MyControl 以自动将焦点转发到其子控件?

最佳答案

如此多的可能性:

  • 使用OnLostFocus事件存储当前控件并计算是否按下了TAB或SHIFT TAB

  • 重写 ProcessKeyPreview 以计算要在 OnGotFocus 中执行的操作 ( SO answer )

  • 覆盖 ProcessCmdKey,如 this answer 所示

关于c# - 在 Control.GotFocus 中检测用户是否向前或向后导航?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9274342/

相关文章:

c# - 将多个文本框和标签放在同一列CSS上?

c# - datagridview 不允许用户删除行

c# - 如何引用 Windows 窗体的所有者?

focus - 如何确保将 wxFrame 置于前台?

c# - 如何只发布需要的依赖?

c# - 绑定(bind)到多个对象

javascript - 当 children 集中注意力时,焦点控制的下拉菜单关闭

javascript - 关注输入 angularjs 不工作

c# - WPF 拾色器实现

c# - 在 Application.Restart() 之前修改命令行参数