locked
TextBox.KeyDown Not Being Triggered For Enter Key

    Question

  • I have a TextBox in which I want to accept only letters and the enter key. To do this, I am using the TextBox.KeyDown and TextBox.KeyUp events. I have everything working fine, except for the fact that the TextBox.KeyDown event isn't being fired for the Enter key. Here is my code:

    Private Sub txtWords_KeyDown(sender As Object, e As KeyRoutedEventArgs) Handles txtWords.KeyDown System.Diagnostics.Debug.WriteLine("txtWords_KeyDown {0} {1} {2}", e.Key.ToString(), CInt(e.Key), Me.txtWords.SelectionStart) If Not (e.Key = VirtualKey.Enter OrElse (e.Key >= VirtualKey.A AndAlso e.Key <= VirtualKey.Z)) Then e.Handled = True End Sub Private Sub txtWords_KeyUp(sender As Object, e As KeyRoutedEventArgs) Handles txtWords.KeyUp System.Diagnostics.Debug.WriteLine("txtWords_KeyUp {0} {1} {2}", e.Key.ToString(), CInt(e.Key), Me.txtWords.SelectionStart) Dim cursorposition As Integer = Me.txtWords.SelectionStart
     Me.txtWords.Text = String.Concat(Me.txtWords.Text.ToUpper().Trim().Where(Function(c As Char) Char.IsLetter(c) OrElse Char.IsWhiteSpace(c))) If Me.txtWords.Text.Length >= cursorposition Then Me.txtWords.SelectionStart = cursorposition Me.SearchWords = Me.txtWords.Text.Split({vbCrLf, vbCr, vbLf, " "}, StringSplitOptions.RemoveEmptyEntries) If Me.SearchWords.Length = 0 Then ApplicationData.Current.LocalSettings.Values.Remove("SearchWords") Else ApplicationData.Current.LocalSettings.Values("SearchWords") = Me.SearchWords End Sub

    When I type the enter key (with the cursor at the end of the TextBox), I get the following output:

    txtWords_KeyUp Enter   13   0

    But take note that I do not get the debug line from txtWords_KeyDown. However, when I type other keys (at least the ones I have tried so far), such as letters and backspace, I do get both debug lines. The most important thing here is that when the user types the enter key the cursor gets moved to the beginning of the TextBox (as you can see from the 0 in the debug line). My basic goal (as far as what I want to allow the user to type) is to let the user input a list of words, one per line. How can I prevent the enter key from sending the cursor to the beginning of the TextBox, and why is the KeyDown event not being triggered for the enter key? Thanks.


    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Sunday, February 16, 2014 5:02 PM

Answers

  • I found the problem, the TextChanged event (which had similar code to the KeyUp event) was interfering and removing the enter too early, my fault. Problem fixed.

    Nathan Sokalski njsokalski@hotmail.com http://www.nathansokalski.com/

    Sunday, February 16, 2014 9:12 PM