处理按键事件+ WinForms +验证+取消

时间:2012-08-27 15:19:11

标签: winforms validation events keypress

我正在C#项目中实现WinForms表单 我的表格是MDI表格的孩子 我的表单包含用户控件 我的用户控件包含一些按钮,包括验证按钮和取消按钮。

我想实现以下逻辑:

  • 当我的表单处于活动状态且用户按下回车键时,我希望自动触发验证按钮单击事件。
  • 当我的表单处于活动状态且用户按下转义键时,我希望自动触发取消按钮单击事件。

如果我的验证和取消按钮未包含在用户控件中,那么我可能会设置表单的AcceptButton和CancelButton属性。

2 个答案:

答案 0 :(得分:2)

以下是我在用户控件的Load事件处理程序中编写的代码,根据Arthur在第一篇帖子的评论中给出的提示:

// 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;

答案 1 :(得分:1)

  1. 从属性设置from true的KeyPreview属性;

  2. 将keyDownEvent添加到表单

  3. 在表单的keyDownEvent中,包含以下代码行

  4. 代码

     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或cancelButton是我假设的按钮名称。你可能有不同的。如果您有不同的名称,请使用您的名字而不是这两个。

相关问题