3

I wonder if there is anyway to change focus from the current control and move it to other control in WPF on TabIndex assigned controls.

Example I have controls with TabIndex 1 to 5, is there a way to jumb the focus from 1 to 5 ?

<TextBox TabIndex="1" Focusable = "true" LostFocus="test_LostFocus"/>
<TextBox TabIndex="2" Focusable = "true"/>
...
<TextBox TabIndex="5" Focusable = "true" name="LastControl"/>

.

private void test_LostFocus(object sender, RoutedEventArgs e)
{
  LastControl.Focus();
}

I tried Keyboard.Focus() and FocusManager.SetFocusedElement() but no luck.

Any idea?

Smith
  • 1,431
  • 4
  • 18
  • 26
  • Where are you calling the `Focus` methods and are you calling it from a background thread? – keyboardP Mar 23 '13 at 14:10
  • Are you sure you want to use the `LostFocus` event? The user may have clicked away from the textbox onto another control. Would you rather just check if the user pressed `tab`/`enter` and only set focus then? – keyboardP Mar 23 '13 at 14:22
  • I'm doing it on `tab` I just left out that part to simplify the question. – Smith Mar 23 '13 at 14:26
  • 1
    In that case, use the `KeyDown` event and handle it yourself (as shown) – keyboardP Mar 23 '13 at 14:29

3 Answers3

2

As stated in the comments, KeyDown is a better way to go (lostfocus will cause weird behaviors such as the user specifically clicking on the second control and the focus goes to the last one instead)...

Make sure you set the e.Handled to true though..!

This will work:

private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
            LastControl.Focus();
        }
 }

Where the deceleration of the textbox should be something like this:

<TextBox TabIndex="1" Focusable = "true" KeyDown="TextBox1_KeyDown"/>
Blachshma
  • 17,097
  • 4
  • 58
  • 72
1

Simply handle the KeyDown event for the textboxes and set focus there. Since you're using Tab, let the control know you'll handle it by setting e.Handled = true, which will stop the default tab action of jumping to the control with the next TabIndex.

private void tb_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Tab)
    {
        e.Handled = true;
        LastControl.Focus();
    }
}
keyboardP
  • 68,824
  • 13
  • 156
  • 205
0

Possible WPF answer, non-programmatic:

Ctrl+Tab / Ctrl+Shift+Tab

Possible WPF answer, programmatic:

System.Windows.Forms.SendKeys.SendWait("^{TAB}"); /

System.Windows.Forms.SendKeys.SendWait("^+{TAB}");

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys.send

https://stackoverflow.com/a/15621425/10789707

Lod
  • 657
  • 1
  • 9
  • 30