Capturing Enter Key press on windows form not working

Capturing Enter Key press on windows form not working



I have a user authentication form with username and password textboxes.There is an okay button that fires the code to validate the credentials.
I want the same code to get executed when the user hits Enter key anywhere on the form.
So i register for the keypress event like this


okay


Enter


this.KeyPress += UserLogin_KeyPress;
private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)

if (e.KeyChar == (char)13)

MessageBox.Show("enter");





This event is not triggered at all.What i'm i doing wrong?






Do you have KeyPreview enable?... Could you try with KeyDown event instead? if (e.KeyCode == Keys.Enter)

– Geraldo Diaz
Sep 13 '18 at 3:37







@GeraldoDiaz Tried,its also not working.

– techno
Sep 13 '18 at 3:40






Is there a reason setting the Form.AcceptButton Property is not a valid solution?

– TnTinMn
Sep 13 '18 at 3:54






@TnTinMn Cool.I did not know about it.It works well.Thanks.

– techno
Sep 13 '18 at 3:56




3 Answers
3



Try setting the property keypreview to true and changing to keydown instead since KeyPress don't support e.Keycode:


private void UserLogin_KeyPress(object sender, KeyEventArgs e)

if (e.KeyCode == Keys.Enter)

MessageBox.Show("Enter");







Thanks for the effort.Keydown is also not working.Welcome to SO.

– techno
Sep 13 '18 at 3:41







Did you try this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frm_KeyPress); What about the keyPreview property in True?

– Geraldo Diaz
Sep 13 '18 at 3:44






setting keypreview to true and changing to keydown solved the issue.Could you please update your answer.

– techno
Sep 13 '18 at 3:51


true






Perfect, done! thank you.

– Geraldo Diaz
Sep 13 '18 at 13:48



Try this:


private void UserLogin_KeyPress(object sender, KeyPressEventArgs e)

if (e.KeyCode == Keys.Enter)

MessageBox.Show("enter");







'KeyPressEventArgs' does not contain a definition for 'KeyCode'

– techno
Sep 13 '18 at 3:38


'KeyPressEventArgs' does not contain a definition for 'KeyCode'






Try to Set AcceptButton property to buttonName.

– ksdev
Sep 13 '18 at 3:52



It's only looking at the form. Controls on the form also need to be wired in.






Please add details to your answer.

– techno
Sep 13 '18 at 3:40



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)