简体   繁体   中英

trigger button click when hitting ENTER?

I have successfully assigned the ENTER key to trigger the button1 click event. When i hit ENTER it should open the form "Startmenu". However it does this TWICE. Not once only. I can't quite find the problem in my code, can someone help me?

This is my code:

public Login()
{
    InitializeComponent();            
    this.textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
}

private void button1_Click_1(object sender, EventArgs e)
{

    if (somethingsomething == true)
    {
        Startmenu sm = new Startmenu();
        sm.Show();
    }

    else
    {
        MessageBox.Show("something");
    }    

}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1.PerformClick();
        e.Handled = true;
    }
}

在button1_Click_1中放置一个断点,然后检查调用堆栈以查看谁触发了调用。

Try This:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1_Click_1.Click(sender,e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM