C#
Enter Key
Key Press
Event Handling
Programming

Enter key press in C

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Detecting Enter key presses in C# differs by application type. In console apps, use Console.ReadKey() and check for ConsoleKey.Enter. In Windows Forms, handle the KeyDown or KeyPress event and check for Keys.Enter. In WPF, handle the KeyDown event and check for Key.Enter. A common use case is submitting a form or triggering a search when the user presses Enter in a text field, without requiring a button click.

Console Applications

Detecting Enter 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. The Key property returns a ConsoleKey enum value.

Waiting for Enter in a Loop

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 entered text (without the Enter character).

Windows Forms

KeyDown Event 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}

e.SuppressKeyPress = true prevents the default "ding" sound that Windows plays when Enter is pressed in a single-line TextBox.

KeyPress Event

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};

AcceptButton (Form-Level Enter Handling)

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 at the form level — pressing Enter anywhere on the form triggers the specified button's Click event.

Handling 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 Applications

KeyDown Event

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}

Using Input Bindings (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}

Preview Events for Tunneling

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};

Use PreviewKeyDown when you need to intercept the key before the control handles it (e.g., preventing the default behavior).

ASP.NET / Blazor

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 (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>

Modifier Keys with Enter

Detect Enter combined 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}

Common Pitfalls

  • Not suppressing the "ding" sound in Windows Forms: Pressing Enter in a single-line TextBox plays a system beep. Set e.SuppressKeyPress = true in KeyDown or e.Handled = true in KeyPress to prevent it.
  • Using KeyPress for special keys: The KeyPress event only fires for character keys, not for function keys, arrow keys, or modifier-only presses. Use KeyDown or KeyUp for non-character keys like Enter, Escape, and Tab.
  • Confusing Keys.Enter and Keys.Return: In Windows Forms, Keys.Enter and Keys.Return have the same numeric value (13). Either works, but Keys.Enter is more readable.
  • Not setting e.Handled = true in WPF: Without marking the event as handled, the Enter key event bubbles up to parent controls, potentially triggering additional handlers or default behaviors.
  • Using AcceptButton when different Enter actions are needed per control: AcceptButton applies to the entire form. If different text boxes need different Enter behavior, use per-control KeyDown handlers instead.

Summary

  • Console apps: use Console.ReadKey() and check key.Key == ConsoleKey.Enter
  • Windows Forms: handle KeyDown event, check e.KeyCode == Keys.Enter, set e.SuppressKeyPress = true
  • WPF: handle KeyDown event, check e.Key == Key.Enter, or use KeyBinding in XAML for MVVM
  • Use AcceptButton in Windows Forms for form-level Enter handling
  • Always suppress the default behavior (e.Handled, e.SuppressKeyPress) to prevent unwanted side effects

Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.