How to keep 1 texbox focused at all times in a WPF?

Dzy Leleur 21 Reputation points
2021-08-11T23:10:02.047+00:00

I have an app, that has a lot of UI controls that are going to be used with the mouse and 1 search box. I want at all times allow the user to type numbers without having to worry about clicking first on the texbox.
How can you achieve this?
Would be routed events the way to go? In that case I would have to route the keydown or keyup event on a the higher lvl parent and then resend it to the textbox? Is this the way to go? Or is there some other way to fix the focus on an element?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,783 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,571 Reputation points Microsoft Vendor
    2021-08-12T10:13:39.93+00:00

    You could try to use the following code to make the focus always on the TextBox.
    The code of xaml:

    <StackPanel >  
            <TextBox Name="textBox1" Focusable="True" FontSize="36"  Height="70">hi</TextBox>  
            <Button Click="Button_Click" Height="60" FontSize="28">click</Button>  
     </StackPanel>  
    

    The code of xaml.cs:

    public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
        }  
         
        private void Button_Click(object sender, RoutedEventArgs e)  
        {  
          MessageBox.Show("clicked");  
        }  
      
        private void Window_GotFocus(object sender, RoutedEventArgs e)  
        {  
          textBox1.Focus();  
        }  
      }  
    

    The picture of the result:
    122696-8.gif


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.