How to cancel a key action in PreviewKeyDown event

Viewed 741

I am trying to detect if user presses ENTER key in a TextBox, and if so, then move focus to a button without preforming a click on the button. So far the only way I have found to detect the ENTER key is using PreviewKeyDown event. For now I can detect the ENTER key but when change focus to the button it fires the Click event. In the normal KeyDown event I could use 'e.handled = true / false', but how do I do this in PreviewKeyDown event ?

2 Answers

Try this:

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
   if (e.KeyCode == Keys.Enter)
   {   
      e.IsInputKey = true;
      button1.Focus();
   }
}

Also, to reduce sound effect you can use the folowing event listener

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   if(e.KeyValue == 13)
   { 
      e.SuppressKeyPress = true;
   }
}

This event PreviewKeyDown is fired before the KeyDown event is fired. It only gives your an preview and you can't set the Handled flag.

Use this event for logging logic, shortcut logic because this will be always fired and can't be stopped by setting a Handled flag.

Related