[英]a custom event for pressing the 'Enter key' in C#
I have a UserControl with some controls and a textbox on it, i want to do some procedures when the Enter key hits on that textbox, I have this code in the UserControl: 我有一个带有一些控件和一个文本框的UserControl,当要在该文本框上按Enter键时,我想执行一些步骤,我在UserControl中有以下代码:
public event EventHandler TextBoxKeyPressed
{
add { textBox.KeyPressed+=value; }
remove { textBox.KeyPressed-=value; }
}
in my main form I have a lot of this control and for each one I should check for the key pressed and if it was Enter key then do the procedures. 在我的主要形式中,我有很多这样的控件,对于每个控件,我应该检查是否按下了键,如果是Enter键,请执行以下步骤。
Is there any way to create a custom event to check the key pressed in the UserControl and if it was Enter Key then fire that event? 有什么方法可以创建自定义事件来检查UserControl中按下的键,如果是Enter键,则触发该事件?
Update: each custom control may have different procedures on KeyPresssd event 更新:每个自定义控件在KeyPresssd事件上可能具有不同的过程
Sure, you can just add, say, an EnterPressed event and fire it when you detect that the Enter key was pressed: 当然,您可以添加一个EnterPressed事件,并在检测到按下Enter键时将其触发:
public partial class UserControl1 : UserControl {
public event EventHandler EnterPressed;
public UserControl1() {
InitializeComponent();
textBox1.KeyDown += textBox1_KeyDown;
}
protected void OnEnterPressed(EventArgs e) {
var handler = this.EnterPressed;
if (handler != null) handler(this, e);
}
void textBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyCode == Keys.Enter) {
OnEnterPressed(EventArgs.Empty);
e.Handled = e.SuppressKeyPress = true;
}
}
}
The event doesn't change, it would still be a normal key pressed event. 该事件没有改变,它仍然是正常的按键事件。 You'd simply only perform the intended action therein if the key was the enter key.
如果键是回车键,则只在其中执行预期的操作。 Something like this:
像这样:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
// the enter key was pressed
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.