简体   繁体   中英

keyDown event is not working on textbox

I a have simple login form and I have set it's accept button property to "OK" button, and I have a textbox "username" which I set it's KeyDown event to do some processing. the Ok has enabled set to false.

btnOk.Enbled = false;  
this.AcceptButton = btnOk;
txtUsername.KeyDown += new KeyEventHandler(KeyDownHandle);

when I hit enter in the username textbox I do some processing and then set accept button enabled to true.

private void KeyDownHandle(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // some processing
        btnOk.Enabled = true;
        txtPassword.Focus();
    }
}

then I write password in password textbox and hit enter so "OK.Click" is triggered.

but the problem is the keyDown is not working because "accept button".
what can I do to solve this?

Edit: Just want to say the problem is resolved if I set acceptButton to "none" but that's not what I'm looking for.

Why don't you remove this.AcceptButton = btnOk from the constrctor (I suppose) and put it in the KeyDownHandler , that way btnOk will accept Enter key only after it is enabled and after the username has been inserted. so the code should be like this:

btnOk.Enabled = false;
txtUsername.KeyDown += new KeyEventHandler(textBox1_KeyDown);
btnOk.Click += new EventHandler(button1_Click);


private void KeyDownHandle(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // some processing
        btnOk.Enabled = true;
        this.AcceptButton = btnOk;
        txtPassword.Focus();
    }
}

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