WPF
C#
UI Development
Focus Management
Windows Applications

Get currently focused element/control in a WPF window

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In WPF, "focused control" usually means the element currently receiving keyboard input. That sounds simple, but WPF actually tracks both keyboard focus and logical focus, and the answer changes depending on which one you need. Understanding the distinction helps you avoid null checks, wrong casts, and event handlers that seem to fire at the wrong time.

Keyboard Focus vs Logical Focus

The fastest way to ask WPF which element currently has keyboard focus is Keyboard.FocusedElement. This returns an IInputElement, so you often cast it to FrameworkElement or a specific control type before using it.

Keyboard focus is global for the application. Only one element can have it at a time, and that element is the one that receives key presses. Logical focus is stored per focus scope. A Window, Menu, or ToolBar can remember which child last had focus even when keyboard focus moves elsewhere.

That distinction matters when a dialog opens, a popup steals focus, or a control lives inside a nested scope. If your code only cares about "what the user is typing into right now", keyboard focus is usually correct. If you need to restore focus later, logical focus is often the better tool.

Reading the Focused Element

Here is a simple window that inspects the currently focused control when a button is clicked:

xaml
1<Window x:Class="FocusDemo.MainWindow"
2        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4        Title="Focus Demo"
5        Height="220"
6        Width="360">
7    <StackPanel Margin="16">
8        <TextBox x:Name="NameBox" Margin="0,0,0,8" />
9        <PasswordBox x:Name="PasswordBox" Margin="0,0,0,8" />
10        <ComboBox x:Name="RoleBox" Margin="0,0,0,8">
11            <ComboBoxItem>Admin</ComboBoxItem>
12            <ComboBoxItem>User</ComboBoxItem>
13        </ComboBox>
14        <Button Content="Show Focused Control" Click="ShowFocusedControl_Click" />
15        <TextBlock x:Name="ResultText" Margin="0,12,0,0" />
16    </StackPanel>
17</Window>
csharp
1using System.Windows;
2using System.Windows.Input;
3
4namespace FocusDemo;
5
6public partial class MainWindow : Window
7{
8    public MainWindow()
9    {
10        InitializeComponent();
11        Loaded += (_, _) => Keyboard.Focus(NameBox);
12    }
13
14    private void ShowFocusedControl_Click(object sender, RoutedEventArgs e)
15    {
16        var focused = Keyboard.FocusedElement as FrameworkElement;
17
18        ResultText.Text = focused is null
19            ? "No keyboard-focused element was found."
20            : $"Focused element: {focused.Name} ({focused.GetType().Name})";
21    }
22}

This approach works well when you only need to inspect focus on demand. Notice the cast to FrameworkElement. Keyboard.FocusedElement can be null, and even when it is not null it may not be the exact control type you expect.

Tracking Focus Changes Reliably

Polling Keyboard.FocusedElement every few seconds is usually the wrong design. WPF already raises routed events for focus changes, so you can react when focus actually moves.

csharp
1using System.Windows;
2using System.Windows.Input;
3
4namespace FocusDemo;
5
6public partial class MainWindow : Window
7{
8    public MainWindow()
9    {
10        InitializeComponent();
11        AddHandler(Keyboard.GotKeyboardFocusEvent,
12            new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus), true);
13    }
14
15    private void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
16    {
17        if (e.NewFocus is FrameworkElement element)
18        {
19            ResultText.Text = $"Now focused: {element.Name} ({element.GetType().Name})";
20        }
21    }
22}

Using AddHandler with handledEventsToo set to true lets the window observe focus changes even when child controls mark events as handled. That makes it a solid choice for diagnostics, form navigation, and accessibility tooling.

Working with Logical Focus

If you need the remembered focused element inside a specific scope, use FocusManager.GetFocusedElement. This is useful when a region of the interface temporarily loses keyboard focus but you want to restore the previous control.

csharp
1using System.Windows;
2using System.Windows.Input;
3
4IInputElement? logicalFocus = FocusManager.GetFocusedElement(this);
5
6if (logicalFocus is FrameworkElement element)
7{
8    ResultText.Text = $"Logical focus: {element.Name}";
9}

For example, a search panel can remember the last text box the user was editing. When the panel becomes active again, you can send focus back to that control instead of guessing.

Common Pitfalls

One common mistake is assuming the focused element always belongs to the current window. If a popup, menu, or another top-level window is active, Keyboard.FocusedElement may point somewhere unexpected or be null.

Another issue is casting directly to a control type such as TextBox without checking. Focus may be on a Button, ComboBoxItem, or even a template-generated element rather than the visible parent control.

Developers also mix up logical and keyboard focus. If code restores focus based on Keyboard.FocusedElement, it may fail after modal interactions because keyboard focus has already moved away. In those cases, store logical focus or track the last meaningful control explicitly.

Finally, querying focus too early is a common source of confusion. During construction, layout may not be complete yet. If initial focus matters, set it after the window has loaded.

Summary

  • Use Keyboard.FocusedElement when you need the control currently receiving keyboard input.
  • Use FocusManager.GetFocusedElement when you need the remembered element inside a focus scope.
  • Cast carefully because the returned value is usually an IInputElement, not a specific control.
  • Prefer focus events over polling when you need to react to changes.
  • Initialize or restore focus after loading so WPF has a valid visual tree to work with.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.