代码之家  ›  专栏  ›  技术社区  ›  Pieter888

C keyEvent不记录Enter/Return键

  •  4
  • Pieter888  · 技术社区  · 16 年前

    我一直在用C制作这个登录表单,我想在用户单击Submit或按下Enter/Return键后立即“提交”所有数据。

    我对keyevents做了一些测试,但到目前为止没有任何效果。

    void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show(e.KeyChar.ToString());
    }
    

    上面的代码是测试事件是否在第一时间起作用。 它工作得很好,当我按“d”时,它会显示“d”,当我按“8”时,它会显示“8”,但按“回车”不会做任何事情。

    所以我认为这是因为enter并没有真正绑定到一个字符,但它确实显示了退格键,它工作得很好,所以我对为什么它没有注册我的enter键感到困惑。

    所以问题是: 如何记录回车键?为什么现在不把按键记录下来?

    注意:我已将事件放入文本框中

    tbPassword.KeyPress += new KeyPressEventHandler(tbPassword_KeyPress);
    

    因此,当选择文本框(当然是整个时间)时按下Enter按钮时,它会触发,这可能与代码的执行有关。

    6 回复  |  直到 13 年前
        1
  •  5
  •   Bill    16 年前

    是否有定义为默认操作的按钮?

    如果是这样,则该控件将吞食Enter键。

    也许这就是你的答案。您需要在提交按钮上将DefaultAction属性设置为true。

        2
  •  0
  •   Anthony Pegram    16 年前

    改为尝试keydown事件。

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            MessageBox.Show("Enter");
        }
    }
    
        3
  •  0
  •   Oskar Kjellin    16 年前

    也许您应该使用表单的“acceptButton”将其设置为提交按钮。你认为这就是你真正的…

        4
  •  0
  •   t0mm13b    16 年前

    你漏掉了一点至关重要的东西,你必须 Handled 属性设置为“真”或“假”,具体取决于条件…

    void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show(e.KeyChar.ToString());
        if (e.KeyCode == Keys.Enter){
          // This is handled and will be removed from Windows message pump
          e.Handled = true; 
        }
    }
    
        5
  •  0
  •   galford13x    16 年前

    试试这个

    textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    
    void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\r')
        {
            MessageBox.Show("Enter Key Pressed", "Enter Key Pressed", MessageBoxButtons.OK);
        }
    }
    
        6
  •  0
  •   Gian Santillan    15 年前

    转到表单…

    在基本形式上改变这个

    formName.acceptButton=按钮名;

    这将读取Enter的密钥日志文件…自动..

    如果不希望用户看到“接受”按钮,可以这样做。

    buttonname.visible=false; formName.acceptButton=按钮名;

    AcceptButton自动从键盘读取Enter键

    推荐文章