C#
Enter Key
Key Press
Event Handling
Programming

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

csharp
1Console.WriteLine("Press Enter to continue...");
2
3ConsoleKeyInfo key = Console.ReadKey(intercept: true);
4
5if (key.Key == ConsoleKey.Enter)
6{
7    Console.WriteLine("\nEnter was pressed!");
8}

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

csharp
1Console.WriteLine("Type commands. Press Enter on an empty line to exit.");
2
3while (true)
4{
5    Console.Write("> ");
6    string input = Console.ReadLine();
7
8    if (string.IsNullOrEmpty(input))
9    {
10        Console.WriteLine("Goodbye!");
11        break;
12    }
13
14    Console.WriteLine($"You entered: {input}");
15}

Console.ReadLine() blocks until Enter is pressed and returns the typed text without the Enter character.

Windows Forms

KeyDown on a TextBox

csharp
1public partial class MainForm : Form
2{
3    public MainForm()
4    {
5        InitializeComponent();
6        searchTextBox.KeyDown += SearchTextBox_KeyDown;
7    }
8
9    private void SearchTextBox_KeyDown(object sender, KeyEventArgs e)
10    {
11        if (e.KeyCode == Keys.Enter)
12        {
13            PerformSearch(searchTextBox.Text);
14            e.SuppressKeyPress = true; // Prevents the "ding" sound
15        }
16    }
17
18    private void PerformSearch(string query)
19    {
20        MessageBox.Show($"Searching for: {query}");
21    }
22}

Pressing Enter in a single-line TextBox plays a system "ding". e.SuppressKeyPress = true prevents it.

KeyPress

csharp
1searchTextBox.KeyPress += (sender, e) =>
2{
3    if (e.KeyChar == (char)Keys.Return)
4    {
5        PerformSearch(searchTextBox.Text);
6        e.Handled = true; // Prevents the ding sound
7    }
8};

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

csharp
1public MainForm()
2{
3    InitializeComponent();
4
5    // Set the form's AcceptButton to trigger on Enter
6    this.AcceptButton = submitButton;
7}
8
9private void submitButton_Click(object sender, EventArgs e)
10{
11    // This fires when Enter is pressed anywhere on the form
12    ProcessForm();
13}

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

csharp
1dataGridView1.KeyDown += (sender, e) =>
2{
3    if (e.KeyCode == Keys.Enter)
4    {
5        e.Handled = true;
6        // Move to next row or process current cell
7        int currentRow = dataGridView1.CurrentCell.RowIndex;
8        ProcessRow(currentRow);
9    }
10};

WPF

KeyDown

csharp
1// XAML
2// <TextBox x:Name="SearchBox" KeyDown="SearchBox_KeyDown" />
3
4private void SearchBox_KeyDown(object sender, KeyEventArgs e)
5{
6    if (e.Key == Key.Enter)
7    {
8        PerformSearch(SearchBox.Text);
9        e.Handled = true;
10    }
11}

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)

xml
1<!-- XAML with command binding -->
2<TextBox Text="{Binding SearchQuery, UpdateSourceTrigger=PropertyChanged}">
3    <TextBox.InputBindings>
4        <KeyBinding Key="Enter" Command="{Binding SearchCommand}" />
5    </TextBox.InputBindings>
6</TextBox>
csharp
1// ViewModel
2public class SearchViewModel : INotifyPropertyChanged
3{
4    public string SearchQuery { get; set; }
5
6    public ICommand SearchCommand => new RelayCommand(() =>
7    {
8        // Executes when Enter is pressed in the TextBox
9        PerformSearch(SearchQuery);
10    });
11}

PreviewKeyDown to intercept Enter first

csharp
1// PreviewKeyDown fires before KeyDown (tunneling event)
2SearchBox.PreviewKeyDown += (sender, e) =>
3{
4    if (e.Key == Key.Enter)
5    {
6        // Handle Enter before the TextBox processes it
7        PerformSearch(SearchBox.Text);
8        e.Handled = true;
9    }
10};

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

razor
1<input @bind="searchQuery" @onkeydown="HandleKeyDown" />
2
3@code {
4    private string searchQuery;
5
6    private void HandleKeyDown(KeyboardEventArgs e)
7    {
8        if (e.Key == "Enter")
9        {
10            PerformSearch(searchQuery);
11        }
12    }
13
14    private void PerformSearch(string query)
15    {
16        // Search logic
17    }
18}

ASP.NET MVC with JavaScript

html
1<input type="text" id="searchBox" />
2
3<script>
4document.getElementById('searchBox').addEventListener('keydown', function(e) {
5    if (e.key === 'Enter') {
6        performSearch(this.value);
7    }
8});
9</script>

Enter with Ctrl, Shift or Alt

csharp
1// Windows Forms
2private void TextBox_KeyDown(object sender, KeyEventArgs e)
3{
4    if (e.KeyCode == Keys.Enter && e.Control)
5    {
6        // Ctrl+Enter pressed
7        SubmitForm();
8    }
9    else if (e.KeyCode == Keys.Enter && e.Shift)
10    {
11        // Shift+Enter pressed — insert new line
12        InsertNewLine();
13    }
14}
15
16// WPF
17private void TextBox_KeyDown(object sender, KeyEventArgs e)
18{
19    if (e.Key == Key.Enter && Keyboard.Modifiers == ModifierKeys.Control)
20    {
21        SubmitForm();
22    }
23}

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms