Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detect Keyboard focus events globally?

Tags:

wpf

The following events can be used, but, they must be attach for each element:

GotKeyboardFocus, LostKeyboardFocus

Is there a way in .NET WPF to globally detect if the focused element changed ? without having to add event listeners for all possible elements ?

like image 579
simo Avatar asked Apr 24 '12 14:04

simo


People also ask

What is keyboard focusable?

When an HTML element is able to handle keyboard input, it is said to have focus. Exactly one element is able to have focus in a time. In most browsers, users can move focus by pressing the Tab key and the Shift + Tab keys.

What is focus event?

The focus event fires when an element has received focus. The event does not bubble, but the related focusin event that follows does bubble. The opposite of focus is the blur event, which fires when the element has lost focus. The focus event is not cancelable.

What does. focus do in c#?

The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.


1 Answers

You can do this in any class with this:

//In the constructor
EventManager.RegisterClassHandler(
        typeof(UIElement),
        Keyboard.PreviewGotKeyboardFocusEvent,
        (KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus);

...

private void OnPreviewGotKeyboardFocus(object sender, 
                                       KeyboardFocusChangedEventArgs e)
{

     // Your code here

}
like image 72
Vaccano Avatar answered Sep 18 '22 20:09

Vaccano