Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 207
Tan Avatar asked Feb 11 '10 08:02

Tan


3 Answers

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

like image 53
Marcel B Avatar answered Oct 06 '22 01:10

Marcel B


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

like image 35
lionheart Avatar answered Oct 06 '22 02:10

lionheart


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;
}
like image 41
Amsakanna Avatar answered Oct 06 '22 00:10

Amsakanna