#307 – Giving Focus to a Control When an Application Starts

A WPF application does not automatically gives keyboard focus to any single control when the application starts.  You can force a control to get focus at application startup by using the Keyboard.Focus static method (in the System.Windows.Input namespace).

Here’s an example that sets focus to one of the TextBox controls in the main window.

        public MainWindow()
        {
   	        this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // On startup, set focus to my first TextBox
            Keyboard.Focus(txtFirst);
        }
Advertisement