#311 – Giving Focus to a Control, Part II

You can give focus to a specific control at run-time using the Keyboard.Focus static method.  You can also give focus to any control that inherits from UIElement using the control’s Focus method.

		public MainWindow()
		{
			this.InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);

		}

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

The difference between these two methods is:

  • Keyboard.Focus just sets keyboard focus
  • UIElement.Focus tries to set keyboard focus.  If the control fails to get keyboard focus, the method sets logical focus to the control

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: