Search code examples
c#wpfkeyboard-events

Making Enter Work Like OK Click In C# WPF Project


I have an OnPreviewKeyDown method which executes an async method when the Enter key is pressed. When the user presses Enter, I try to move the focus away and execute the action (vm.ProcessSelectedDocumentCommand.Execute(null), but an error is generated related to that action. The error occurs when the focus is on a control, like a textbox, which means the user is in the middle of an edit. That is why I try to move the focus elsewhere...to the OK button in this case. I also disable the button to make sure the user doesn't press twice.

If the user clicks the OK button instead, which simply executes the action, then everything works fine. What am I doing wrong here and how can I make the Enter work more like a click?

        private void OnPreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                btnProcess.Focus();
                btnProcess.IsEnabled = false;
                vm.ProcessSelectedDocumentCommand.Execute(null);
            }
        }

I expected the Enter key to process the action the same way that the click does, considering that they both call the same method.


Solution

  • This seems straight forward. Add an AcceptsReturn="false" to the TextBox, and add a IsDefault="True" to the Button. Then when you hit enter, while in the TextBox, the button will fire instead

    Dont forget to remove your OnPreviewKeyDown handler code - it is not necessary