#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: #311 – Giving Focus to a Control, Part II « 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: