我正在C#项目中实现WinForms表单 我的表格是MDI表格的孩子 我的表单包含用户控件 我的用户控件包含一些按钮,包括验证按钮和取消按钮。
我想实现以下逻辑:
如果我的验证和取消按钮未包含在用户控件中,那么我可能会设置表单的AcceptButton和CancelButton属性。
答案 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)
从属性设置from true的KeyPreview属性;
将keyDownEvent添加到表单
在表单的keyDownEvent中,包含以下代码行
代码
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是我假设的按钮名称。你可能有不同的。如果您有不同的名称,请使用您的名字而不是这两个。