正在捕获PictureBox上的KeyDown事件



我知道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;
}
}
}

我做错了什么?

您关注的是FORM,而不是PictureBox。

更改:

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
Focus();
}

收件人:

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
pictureBox1.Focus();
}

最新更新