How to get the focused control in WPF?
Asked Answered
T

3

5

How can I get a current focused control in WPF?

I found some solution for WinForms, but invoking WIN32 API function, didn't work in WPF?

Is there any way for doing it in WPF?

Tiv answered 15/3, 2011 at 19:47 Comment(0)
T
6

Here's what I did

protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
    lostFocusControl = e.OldFocus;
}

private void PauseButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // invoke OnPreviewLostKeyboardFocus handler
}
Tiv answered 18/3, 2011 at 14:43 Comment(1)
Is there a way to do it in XAML itself ?Joplin
T
7

I know this is a late answer, but maybe people searching can find this helpful, I it found on msdn in the "Navigating Focus Programmatically" section close to the bottom of the page:

UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
Transformer answered 17/9, 2014 at 8:59 Comment(0)
T
6

Here's what I did

protected override void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEventArgs e)
{
    lostFocusControl = e.OldFocus;
}

private void PauseButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // invoke OnPreviewLostKeyboardFocus handler
}
Tiv answered 18/3, 2011 at 14:43 Comment(1)
Is there a way to do it in XAML itself ?Joplin
S
0

Another solution:

bool FocusedElement = FocusManager.GetFocusedElement(this);

Found here: https://mcmap.net/q/1251199/-finding-out-which-control-has-focus-duplicate

Supra answered 25/8, 2023 at 6:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.