Reputation: 744
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
Upvotes: 1
Views: 3550
Reputation: 941465
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;
}
}
}
Upvotes: 5
Reputation: 218827
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
}
}
Upvotes: 1