【发布时间】:2025-11-26 21:40:01
【问题描述】:
我知道 PictureBox 没有 KeyDown 事件,但我真的很想捕捉该事件。我使用的是 Form 的 KeyDown 事件,但是当小部件太多时会出现问题,所以我别无选择,只能将关键事件附在 PictureBox 中。在文档中,它说 PreviewKeyDown 用于在焦点位于 PictureBox 时捕获关键事件。我已经尝试通过使用 MouseEnter 将焦点设置在小部件上来做到这一点,但它只是不监听关键事件。
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.H:
MessageBox.Show("Pressed button");
break;
}
}
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
Focus();
}
private void pictureBox1_MouseLeave(object sender, EventArgs e)
{
ActiveControl = null;
}
}
}
我做错了什么?
【问题讨论】:
-
制作一个从 PictureBox 派生的自定义控件,然后在其构造函数中添加
SetStyle(ControlStyles.Selectable | ControlStyles.UserMouse, true);。由于您在那里,您还可以覆盖OnKeyDown,并在需要时引发事件。 PreviewKeyDown 无论如何都会起作用。 -
焦点错误。由于缺少其他基本的 GUI 功能,您无法告诉您有此错误,实际上能够查看哪个小部件具有焦点。绘制焦点矩形非常简单,例如is here。