开发者

C# KeyEvent doesn't log the enter/return key

I've been making this login form in C# and I wanted to 'submit' all the data as soon as the user either clicks on submit or presses the enter/return key.

I've been testing a bit with KeyEvents but nothing so far worked.

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

The above code was to test if the event even worked in the first place. It works perfectly, when I press 'd' it shows me 'd' when I press '8' it shows me '8' but pressing enter doesn't do anything.

So I though this was because enter isn't really bound to a character but it did show backspace, it worked just fine so it got me confused about why it didn't register my enter key.

So the question is: How do I lo开发者_C百科g the enter/return key? and why doesn't it log the key press right right now like it should?

note: I've put the event in a textbox

tbPassword.KeyPress += new KeyPressEventHandler(tbPassword_KeyPress);

So it fires when the enter button is pressed WHILE the textbox is selected (which is was the whole time of course) maybe that has something to do with the execution of the code.


Do you have a button defined as the default action?

If so then that control will gobble up the Enter key.

And maybe that is your answer. You need to set the DefaultAction property to true on your submit button.


Try the KeyDown event instead.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        MessageBox.Show("Enter");
    }
}


Perhaps you should use the "AcceptButton" of the form to set it to the submit button. Think that is what you what really...


You have left out a vital bit, you must set the Handled property to true or false depending on the condition...

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; 
    }
}


Try this

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);
    }
}


go to your forms...

in the basic form change this

FormName.AcceptButton = buttonName;

this would read the key log file of enter... automatically..

you can do this if you dont want users to see accept button

buttonName.Visible = false; FormName.AcceptButton = buttonName;

AcceptButton automatically reads the enter key from the keyboard

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜