简体   繁体   中英

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:

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.

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?

Update: each custom control may have different procedures on KeyPresssd event

Sure, you can just add, say, an EnterPressed event and fire it when you detect that the Enter key was pressed:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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