Вопрос

I have the following code which does not show the MessageBox when enter/return is pressed.

For any other key(i.e. letters/numbers) the MessageBox shows False.

private void cbServer_TextChanged(object sender, EventArgs e)
{
    if (enterPressed)
    {
        MessageBox.Show("Enter pressed");
    }
    else
        MessageBox.Show("False");
}

private void cbServer_Keydown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
    {
        enterPressed = true;
        MessageBox.Show("Enter presssed: " + enterPressed);

    }
    else
        enterPressed = false;
}

Any ideas?

EDIT: Above code, I thought the issue was with the _Keydown even so I only posted that.

Это было полезно?

Решение

This is because when you press Enter TextChanged event won't fire.

Другие советы

in your form designer class (formname.designer.cs) add this :

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Login_KeyPress);

and add this code to backbone code (formname.cs):

void Login_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
            MessageBox.Show("ENTER has been pressed!");
        else if (e.KeyChar == (char)27)
            this.Close();
    }
private void textBox_PreviewKeyDown(object sender, KeyEventArgs e)
 {
            if (e.Key == Key.Enter)
            {
                MessageBox.Show("Enter key pressed");
            }
            else if (e.Key == Key.Space)
            {
                MessageBox.Show("Space key pressed");
            }
}

Use PreviewKeyDown event to detect any key before shown in textbox or input

void cbServer_PreviewKeyDown(object sender, System.Windows.Forms.PreviewKeyDownEventArgs e)
    {

        // Check if User Presses Enter
        if (e.KeyCode == System.Windows.Forms.Keys.Return)
        {
            // Here: user pressed ENTER key

        }
        else
        {
            // Here: user did not press ENTER key
        }
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top