mafap
mafap

Reputation: 391

key pressed down not working as expected

I have text box where I want to send data (myButton) when I press Return.

private void txtBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Shift && e.KeyCode == Keys.Return)
    {
        // Shift + Return
    }
    else if (e.KeyCode == Keys.Return)
    {
        // Return
        if (!String.IsNullOrWhiteSpace(txtBox.Text))
            myButton.PerformClick();
    }
}

This works fine if I have some text but when I don't have text, if I press Return it adds a new line and I don't want that. Any sugestion?

Upvotes: 1

Views: 79

Answers (1)

Hans Passant
Hans Passant

Reputation: 942548

If you don't want lines to be added to the TextBox then you should set its Multiline property to False.

Generally, if you don't want the Enter key to be processed then you'll need to prevent the KeyPress event for it from firing. Which you do by setting the e.SuppressKeyPress property to true. Fix:

else if (e.KeyCode == Keys.Return)
{
    // Return
    if (!String.IsNullOrWhiteSpace(txtBox.Text))
        myButton.PerformClick();
    e.Handled = e.SuppressKeyPress = true;
}

Upvotes: 1

Related Questions