Reputation: 1697
I am implementing a WinForms form in a C# project.
My form is a child of a MDI form.
My form contains a user control.
My user control contains some buttons including a validation button and a cancel one.
I want to implement the following logic :
If my validation and my cancel buttons were not included in a user control then I would probably set the AcceptButton and CancelButton properties of my form.
Upvotes: 0
Views: 673
Reputation: 8419
Set the KeyPreview Property of your from true from properties;
Add keyDownEvent to your Form
In keyDownEvent of your Form, include following lines of code
The code
if(e.KeyValue==13)// When Enter Key is Pressed
{
// Last line is performing click. Other lines are making sure
// that user is not writing in a Text box
Control ct = userControl1 as Control;
ContainerControl cc = ct as ContainerControl;
if (!(cc.ActiveControl is TextBox))
validationButton.PerformClick(); // Code line to performClick
}
if(e.KeyValue==27) // When Escape Key is Pressed
{
// Last line is performing click. Other lines are making sure
// that user is not writing in a Text box
Control ct = userControl1 as Control;
ContainerControl cc = ct as ContainerControl;
if (!(cc.ActiveControl is TextBox))
cancelButton.PerformClick(); // Code line to performClick
}
validationButton or cancelButton are the names of your buttons which I am just supposing. You may have different ones. Use Your names instead of these two if you have different.
Upvotes: 1
Reputation: 1697
Here is the code I have written in the Load event handler of my user control according to a tip given by Arthur in a comment to my first post :
// Get the container form.
form = this.FindForm();
// Simulate a click on the validation button
// when the ENTER key is pressed from the container form.
form.AcceptButton = this.cmdValider;
// Simulate a click on the cancel button
// when the ESC key is pressed from the container form.
form.CancelButton = this.cmdAnnulerEffacer;
Upvotes: 2