在基本表单级别执行事件

时间:2012-10-10 22:58:29

标签: c# winforms

这似乎相当简单,但我无法完成它。我有一个BaseForm类,我的应用程序中的每个表单都继承。

我只想在每次按下任何继承BaseForm的形式的键时执行一行代码。在我的BaseForm中,我尝试了以下但没有运气:

public class BaseForm : Form
{
     protected override void OnKeyPress(KeyPressEventArgs e)
     {
          //Perform action
     }

}

public class MainForm : BaseForm
{
     //All of my main form code goes here.
}

任何帮助将不胜感激!提前致谢

2 个答案:

答案 0 :(得分:2)

您可能需要将基本表单的KeyPreview设置为true,以便能够从任何控件中捕获所有按键。考虑在表单设计器或基类构造函数中执行此操作。我猜您在派生表单上有一些编辑器(例如文本框),因此您需要将KeyPreview设置为true,以便基本表单能够捕获这些按键

您可以覆盖OnKeyPress方法(如您的问题所示),也可以在基本表单中为KeyPress事件添加事件处理程序。

public class BaseForm : Form
{
     public BaseForm()
     {
         this.KeyPreview = true; //it's necessary!! 

         //or just override the OnKeyPress method instead
         this.KeyPress += new KeyPressEventHandler(BaseForm_KeyPress);
     }

     private void BaseForm_KeyPress(object sender, KeyPressEventArgs e)
     {
         //do your action
     }
}

答案 1 :(得分:0)

到目前为止你所做的是正确的。如果你的OnKeyPress没有被执行那么你就有问题了 - 你有一个干扰的OnKeyDown吗?

您接下来要做的是在派生表单中使用相同的覆盖:

public class MainForm : BaseForm
{
     //All of my main form code goes here.

     protected override void OnKeyPress(KeyPressEventArgs e)
     {
          //do whatever action this form needs to, if any

          base.OnKeyPress(e);
     }
}

看到base.OnKeyPress的来电?这将执行您在基础中的代码行。请注意,您可以将该调用放在函数中的任何位置,在表单特定代码之前的开头可能更合适。