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 ?
4
votes
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 sound
– Budapest
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 key
– Budapest
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;
}
}