How to simulate enter key c# code example

Example 1: c# keyboard enter

You must try this in keydown event

here is the code for that :

private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            MessageBox.Show("Enter pressed");
        }
    }
Update :

Also you can do this with keypress event.

Try This :

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == Convert.ToChar(Keys.Return))
        {
            MessageBox.Show("Key pressed");
        }
    }

Example 2: c# enter key press console

// ---------- How to detect when the input is ENTER? ----------- //

string input = "";

// 1º Method
while(true)
{
  Console.WriteLine("Write something (or hit ENTER to quit): ");
  input = Console.ReadLine();
  
  if( string.IsNullOrWhiteSpace(input)) )
    break;
  else
    // some code...
  
}


// 2º Method
while(true)
{
  Console.WriteLine("Write something (or hit ENTER to quit): ");
  input = Console.ReadLine();
  
  if( input.Equals("") )
    break;
  else
    // some code...
  
}