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?

lance
  • 16,092
  • 19
  • 77
  • 136
  • What if the focus leaves the control because some other control grabs the focus [in code](http://msdn.microsoft.com/en-us/library/system.windows.uielement.focus.aspx)? – Vlad Jun 14 '11 at 13:59
  • 2
    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. – Kibbee Jun 14 '11 at 14:09
  • 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 example – Damascus Jun 14 '11 at 14:20
  • 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... – lance Jun 14 '11 at 14:24
  • 2
    I'm intrigued as to why you'd need to make this differentiation. Can you elaborate? – Kent Boogaart Jun 14 '11 at 15:15
  • Can you use Keyboard.IsKeyDown(Keys.Tab)? – Steven Jun 19 '11 at 20:10

1 Answers1

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?

Philipp Schmid
  • 5,778
  • 5
  • 44
  • 66
  • 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. – ygoe Jul 30 '12 at 07:54