I know there is no KeyDown event for PictureBox, but I really want to capture that event. I was using the Form's KeyDown event but it becomes problematic when there are too many widgets, so I don't have any choice but enclose the key events to the PictureBox. In the documentation, it says that PreviewKeyDown is used to capture key events when the focus is on PictureBox. I have tried doing that by setting the focus on the widget with MouseEnter, but it just doesn't listen for key events.
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;
}
}
}
What am I doing wrong?