Windows apps
Collapse the table of content
Expand the table of content
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Keyboard.GotKeyboardFocus Attached Event


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Occurs when an element receives keyboard focus.

Namespace:   System.Windows.Input
Assembly:  PresentationCore (in PresentationCore.dll)

See AddGotKeyboardFocusHandler, RemoveGotKeyboardFocusHandler

This is an attached event. WPF implements attached events as routed events. Attached events are fundamentally a XAML language concept for referencing events that can be handled on objects that do not define that event, which WPF expands upon by also enabling the event to traverse a route. Attached events do not have a direct handling syntax in code; to attach handlers for a routed event in code, you use a designated Add*Handler method. For details, see Attached Events Overview.

Keyboard focus refers to the object that is receiving keyboard input. The element with keyboard focus has IsKeyboardFocused set to true. There can be only one element with keyboard focus on the entire desktop. Logical focus refers to the object within a focus scope that has focus. For more information on focus, keyboard focus, and logical focus, see Input Overview and Focus Overview.

If the PreviewGotKeyboardFocus event or the PreviewLostKeyboardFocus event is handled, keyboard focus does change.

Identifier field


Routing strategy




The following example creates a TextBox and attaches event handlers for the GotKeyboardFocus event and the LostKeyboardFocus event. When the TextBox obtains keyboard focus, the background color is changed and the text of the TextBox is cleared. When the TextBlock loses keyboard focus, the background color is changed and a method is called which resets variables used in the sample.

<Border BorderBrush="Black" BorderThickness="1"
        Width="200" Height="100" Margin="5">
    <Label HorizontalAlignment="Center" Content="Type Text In This TextBox" />
    <TextBox Width="175"
private void TextBoxGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    TextBox source = e.Source as TextBox;

    if (source != null)
        // Change the TextBox color when it obtains focus.
        source.Background = Brushes.LightBlue;

        // Clear the TextBox.
private void TextBoxLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
    TextBox source = e.Source as TextBox;

    if (source != null)
        // Change the TextBox color when it loses focus.
        source.Background = Brushes.White;

        // Set the  hit counter back to zero and updates the display.
Return to top
© 2018 Microsoft