Detect Enter Key C#

后端 未结 4 1801
无人及你
无人及你 2021-01-17 15:24

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.

<
相关标签:
4条回答
  • 2021-01-17 16:01

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

    0 讨论(0)
  • 2021-01-17 16:11

    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();
        }
    
    0 讨论(0)
  • 2021-01-17 16:19
    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

    0 讨论(0)
  • 2021-01-17 16:19
    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
            }
        }
    
    0 讨论(0)
提交回复
热议问题