4
votes

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
if (SuppressKeyPress) => PeekMessage() + PM_REMOVE. Of course, you also have e.IsInputKey there...Jimi
@Jimi thank you for response, getting error when I add this (SuppressKeyPress) is there a using statement or something else required to implement?Budapest
Those are not suggestions, those are links to the internal functionality. Do you want the enter key to perform its default action in the TextBox (enter a new line in a multiline TextBox) before you focus the Button? Do you have a multiline TextBox or is it single line?Jimi
ok I will check the links. To answer your question, it is not multiline and goal is to move focus to button when user presses ENTER key while in the TextBox (similar behavior as pressing Tab) the 'e.IsInputKey' works but gives an alert soundBudapest
NOTE: because I am using the 'AcceptButton' property, this seems to stop the 'KeyDown' event from capturing ENTER key, so I have to use 'PreviewKeyDown' to detect the ENTER keyBudapest

2 Answers

2
votes

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

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.