Detect the Enter key press in C# (console, WinForms, WPF, Blazor)
Codemia Knowledge Hub ·
How you detect the Enter key in C# depends on the application type. In console apps, call Console.ReadKey() and check for ConsoleKey.Enter. In Windows Forms, handle KeyDown (or KeyPress) and check for Keys.Enter. In WPF, handle KeyDown and check for Key.Enter. The usual goal is to submit a form or run a search when the user presses Enter in a text field, without clicking a button.
Console applications
Reading a single key with ReadKey
Console.ReadKey(intercept: true) reads a key without displaying it. Its Key property is a ConsoleKey enum value.
Reading lines until Enter on an empty line
Console.ReadLine() blocks until Enter is pressed and returns the typed text without the Enter character.
Windows Forms
KeyDown on a TextBox
Pressing Enter in a single-line TextBox plays a system "ding". e.SuppressKeyPress = true prevents it.
KeyPress
In KeyPress, set e.Handled = true to stop the ding. Keys.Enter and Keys.Return have the same numeric value (13), so either works, but Keys.Enter reads better. KeyPress only fires for character keys, not for function keys, arrow keys or modifier-only presses, so use KeyDown or KeyUp for those.
AcceptButton for form-level Enter
AcceptButton is the simplest way to handle Enter for the whole form: pressing Enter anywhere on the form triggers that button's Click event. Because it applies to the entire form, use per-control KeyDown handlers instead when different text boxes need different Enter behavior.
Enter in a DataGridView
WPF
KeyDown
Set e.Handled = true. Otherwise the Enter key event bubbles up to parent controls and can trigger additional handlers or default behavior.
KeyBinding with a command (MVVM)
PreviewKeyDown to intercept Enter first
PreviewKeyDown is a tunneling event that fires before KeyDown. Use it when you need to intercept the key before the control handles it, for example to prevent the default behavior.
Blazor and ASP.NET
Blazor
ASP.NET MVC with JavaScript
Enter with Ctrl, Shift or Alt
Related reading
- Enter symbol into a text Label in Windows Forms?
- Entity Framework - Cannot convert lambda expression to type 'string' because it is not a delegate type
- Entity Framework - Code First - Can't Store ListString
- Entity Framework - Invalid Column Name '_ID when not using entity connection string
- Entity Framework 4 - AddObject vs Attach
- Entity Framework 4 mapping fragment error when adding new entity scalar
- Entity Framework 4 Single vs First vs FirstOrDefault
- Entity Framework 5 Updating a Record

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.