简体   繁体   中英

Is there a Keyboard Shortcut to Focus on a Known Tabindex

When a Windows Form has the focus you can step through any Controls that have their TabStop Property set True, in Tabindex Order, by pressing the {TAB} Key.

Similarly, you can step through them in reverse order using {Shift+ TAB}

Is there any Keyboard Shortcut to move the Focus to a Known, or Absoulte, Tabindex (for example the Lowest or Highest), rather than moving it Relative to the Active Control?

If so does MS document this anywhere?

There's nothing out of the box to do this, AFAIK. You'd need to do it yourself. However, it's not that difficult, you just need to check for a hotkey by overriding the ProcessCmdKey method and then call Control.Focus() for the appropriate control:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.D1))
    {
        textBox1.Focus();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

You can even take it a step further to have shortcuts for several controls and also have the ability to manage the controls and their shortcuts at run-time by having a dictionary that holds the shortcuts and the controls to be focused:

Dictionary<Keys, Control> FocusShortcuts;

public Form1()
{
    InitializeComponent();

    FocusShortcuts = new Dictionary<Keys, Control>();
    FocusShortcuts.Add(Keys.Control | Keys.D1, textBox1);
    FocusShortcuts.Add(Keys.Control | Keys.D2, textBox2);
    FocusShortcuts.Add(Keys.Control | Keys.D3, textBox3);
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    Control control;
    if (FocusShortcuts.TryGetValue(keyData, out control))
    {
        control.Focus();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

Update

If instead, you want to set the focus to a control by its Tab Order, you can replace textBox1.Focus(); with something like this:

int someIndex = 5;
Control control = this.Controls.OfType<Control>()
                      .FirstOrDefault(c => c.TabIndex == someIndex);
if (control != null) control.Focus();

You'd just need to change the value of someIndex to the index of your choice and change this with the control's container (you can leave it if the container is the current form/UserControl).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM