Did user use keyboard or mouse to leave WPF TextBox?
Asked Answered
W

1

8

I have a handler for the TextBox's PreviewLostKeyboardFocus event. It fires when I leave the TextBox using the keyboard (Tab key) or the mouse (by clicking on another TextBox on the form).

The handler takes a KeyboardFocusChangedEventArgs, which has a property named KeyboardDevice, which isn't null in either scenario (I was hoping to find null here when using the mouse).

Question: How can I tell whether a user used the keyboard or the mouse to leave a WPF TextBox?

Wilkison answered 14/6, 2011 at 13:56 Comment(6)
What if the focus leaves the control because some other control grabs the focus in code?Implore
Wouldn't it be better to set up a key listener and detect if tab was pressed? If tab as pressed, you can respond accordingly, Otherwise assume they left some other way, such as by the mouse. I'm not that familiar with WPF, but in many UI libraries you can capture the tab key, and override the action of it. I'm guessing you actually want to insert a tab into the text area instead of leaving going to the next field.Croton
I agree with Kibbee here: how about just either adding an EventHandler for the Tab key, or a MouseOver handler which turns a specific boolean to true if called for examplePetrol
Those are helpful suggestions. A simple response, though: I assumed a framework as robust as WPF would give me this information easily. Bad assumption, I suppose...Wilkison
I'm intrigued as to why you'd need to make this differentiation. Can you elaborate?Lotta
Can you use Keyboard.IsKeyDown(Keys.Tab)?Jolandajolanta
C
3

The e.KeyboardDevice.GetKeyStates(Key.Tab) (where e is of type KeyboardFocusChangedEventArgs) reports:

  • None (when mouse was used to change focus)
  • Down, Toggled (when TAB was use to leave the TextBox)

Would that work for you?

Calibre answered 23/6, 2011 at 19:59 Comment(1)
I had this idea too, today, but thought there may be a timing issue because you have two distinct events here. And another comment here observed the same: That would work in 90% of the cases, depending on whether the event was triggered while the key was still pressed. I wouldn't rely on that.Sagittarius

© 2022 - 2024 — McMap. All rights reserved.