user1139666
user1139666

Reputation: 1697

Handling Key Pressed Events + WinForms + Validation + Cancel

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

Answers (2)

Sami
Sami

Reputation: 8419

  1. Set the KeyPreview Property of your from true from properties;

  2. Add keyDownEvent to your Form

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

user1139666
user1139666

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

Related Questions