KeyDown event is not firing when pressing enter in an UserControl

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-04 14:16:11

问题


I have a UserControl for an application and with a textbox. When pressing enter in this textbox a button should be activated (basically pressing 'Ok' via pressing Enter instead of clicking the button manually with the mouse).

So I added a KeyDown event to my textbox and implemented the following code:

private void txtSearchID_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
    {
       button_Click(null, null);
    }
}

But when I wanted to test this nothing happened when pressing Enter. Strangely enough in addition to that the event does not even get fired when pressing Enter but with every other key. Am I missing something?


回答1:


This is because, when a key is pressed it will go to the control which has focus on the form, as the KeyPreview property of Form is set to False by default. You change the event like this

Change to KeyUP event,

private void txtSearchID_Keyup(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && !txtSearchID.Text.Equals(string.Empty))
    {
       button_Click(null, null);
    }
}


来源:https://stackoverflow.com/questions/22193983/keydown-event-is-not-firing-when-pressing-enter-in-an-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!