c# - 带有 OnKeyDown 和其他控件的 Winforms
问题描述
我有一个 Windows.Form 我覆盖OnKeyDown
override protected void OnKeyDown(KeyEventArgs e) {
// do things on specific key presses
}
这一切正常,直到我添加我的按钮
class MyWinForm : Form {
static System.Windows.Forms.Timer Timer = new System.Windows.Forms.Timer();
static EventHandler EveryTick;
private System.Windows.Forms.Button button1;
public MyWinForm() {
Width = 300;
Height = 300;
Text = "MyWinForm";
this.button1 = new System.Windows.Forms.Button();
this.button1.Text = "Start";
this.button1.Size = new System.Drawing.Size(100,50);
this.button1.Location = new System.Drawing.Point(10, Height -80);
this.button1.Click += new System.EventHandler(ButtonClick);
this.Controls.Add(this.button1);
}
static void Main() {
// Some more stuff is happening here
Application.Run(new MyWinForm());
}
一旦我添加this.Controls.Add(this.button1);
我的 OnKeyDown 就不再工作了。
解决方案
所有键盘事件总是转到具有焦点的控件。在没有任何控件的表单中,接收所有键盘事件的是表单本身,除非您将属性KeyPreview设置为true
.
在添加按钮之前,表单上的事件是唯一处理事件的候选者,但是在添加按钮之后,默认情况下,它成为所有事件的接收者。设置KeyPreview
为true
将表单恢复为所有键盘事件的接收者。
推荐阅读
- .net-core - 使用 .AsExpandable() 时 .Include() 的 EF Core 3 问题
- spacy - 优化 spaCy 命名实体识别以提高精度
- c# - 在复杂的 linq 查询中拆分和包含内部子句
- javascript - Panolens + p5js:使用带有 SLIDERS 的图像 BLEND SCREEN 功能用于 PANORAMA 图片
- java - 使用mongodb的javascript json解析查询
- azure-active-directory - Azure AD 和 Azure AD B2C 用户帐户之间是否可以连接?
- ruby-on-rails - Rails:如何在 with_lock 块内回滚活动记录?
- java - 在 Maven 中仅构建更改的模块
- ios - 带有标题部分的插入分组 UITableView
- image - 在加载高分辨率图像时显示加载小部件