1

这似乎很简单,但我无法完成它。我有一个 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.
}

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

4

2 回答 2

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
     }
}
于 2012-10-10T23:38:21.450 回答
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吗?这将执行您在基础中拥有的那行代码。请注意,您可以将该调用放在函数中的任何位置,将其放在表单特定代码之前的开头可能更合适。

于 2012-10-10T23:07:25.893 回答