Tan
Tan

Reputation: 2178

WPF always focus on a textbox

I want to always Focus on a specific TextBox on my WPF application whenever I click on anything on the application it should always focus on the TextBox.

Upvotes: 6

Views: 5754

Answers (3)

lionheart
lionheart

Reputation: 433

There is an event handler MouseLeftMouseButton. When the event handler was triggered, use textbox.Focus() inside the handler.

Upvotes: 2

Amsakanna
Amsakanna

Reputation: 12934

If i'm right, your intention is to get the keyboard commands and display the char pressed into your textbox even if the focus is on other controls.

If that is the case, you can route the keyboard commands to the root control (control in the top level... eg: window), analyse them and display in the textbox. I'ld try to give examples if that helps.

EDIT:

private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
  if (Keyboard.Modifiers != ModifierKeys.Shift)
  {
    if (e.Key > Key.A && e.Key < Key.Z)
    {
      textBox1.Text += e.Key.ToString().ToLower();
    }
  }
  else
  {
    if (e.Key > Key.A && e.Key < Key.Z)
    {
      textBox1.Text += e.Key.ToString();
    }
  }            
  e.Handled = true;
}

Upvotes: 1

Marcel B
Marcel B

Reputation: 3664

Add to the TextBox.OnLostFocus event a handler which sets the focus to the TextBox.

Upvotes: 7

Related Questions