1

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?

atachsin
  • 173
  • 10
  • Make a Custom Control, derived from PictureBox, then add `SetStyle(ControlStyles.Selectable | ControlStyles.UserMouse, true);` in its Constructor. Since you're there, you can also override `OnKeyDown`, and raise the event, if needed. PreviewKeyDown will work anyway. – Jimi Oct 10 '20 at 14:38
  • Wrong focus. You could not tell you had this bug because of the other essential GUI feature that is missing, actually being able to *see* which widget has the focus. Drawing a focus rectangle is really easy, example [is here](https://stackoverflow.com/a/3562449/17034). – Hans Passant Oct 10 '20 at 14:43

1 Answers1

2

You're giving focus to the FORM, not the PictureBox.

Change:

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

To:

private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
    pictureBox1.Focus();
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40