当按下UserControl中的Enter时,不会触发KeyDown事件 [英] KeyDown event is not firing when pressing enter in an UserControl

查看:95
本文介绍了当按下UserControl中的Enter时,不会触发KeyDown事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于应用程序的UserControl和一个文本框.在此文本框中按Enter时,应激活一个按钮(基本上是通过按Enter来按确定",而不是用鼠标手动单击该按钮.)

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).

因此,我在文本框中添加了一个KeyDown事件,并实现了以下代码:

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

但是当我想测试时,按Enter键没有任何反应.奇怪的是,按Enter时,其他所有键都不会触发该事件.我想念什么吗?

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?

推荐答案

这是因为,当按下某个键时,它将转到具有焦点的控件,因为Form的KeyPreview属性被设置为False.默认.您可以这样更改事件

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

更改为KeyUP事件,

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

这篇关于当按下UserControl中的Enter时,不会触发KeyDown事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆