简体   繁体   English

按Enter键进入UserControl时,不会触发KeyDown事件

[英]KeyDown event is not firing when pressing enter in an UserControl

I have a UserControl for an application and with a textbox. 我有一个用于应用程序的UserControl和一个文本框。 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). 当按下此文本框中的Enter键时,应该激活一个按钮(通过按Enter键按“确定”,而不是用鼠标手动单击按钮)。

So I added a KeyDown event to my textbox and implemented the following code: 所以我在我的文本框中添加了一个KeyDown事件并实现了以下代码:

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. 但是当我想测试时,按Enter键时没有发生任何事情。 Strangely enough in addition to that the event does not even get fired when pressing Enter but with every other key. 除此之外,奇怪的是,当按Enter键时,事件甚至不会被触发,而是每隔一个键。 Am I missing something? 我错过了什么吗?

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. 这是因为,当按下某个键时,它将转到注重表单的控件,因为默认情况下Form的KeyPreview属性设置为False。 You change the event like this 你改变这样的事件

Change to KeyUP event, 更改为KeyUP事件,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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