C#C
C#3y ago
Eris

❔ Form not detecting key presses

Heyo! I can't figure out why this form doesn't take key presses.

I'm working in a .NET Windows Forms app, and I have a Form where I want to move a pictureBox using the arrow keys. I've set the form's
KeyPreview = true
property and set its KeyDown event to my method, tried both in designer and by writing
this.Keydown += Form_KeyDown;
in code, as well as both simultaneously. However no key press triggers the method. I have double-clicked the Event in the form editor many times to check again whether the Event is linked to the correct method and it definitely is. The method in question:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show("here!");
    if (e.KeyCode == Keys.Left)
    {
        zoomReticle.Location = new Point(zoomReticle.Location.X - 1, zoomReticle.Location.Y);
        e.SuppressKeyPress = true;
        updateReticle();
    }
    if (e.KeyCode == Keys.Up)
    {
        zoomReticle.Location = new Point(zoomReticle.Location.X, zoomReticle.Location.Y - 1);
        e.SuppressKeyPress = true;
        updateReticle();
    }
    if (e.KeyCode == Keys.Right)
    {
        zoomReticle.Location = new Point(zoomReticle.Location.X + 1, zoomReticle.Location.Y);
        e.SuppressKeyPress = true;
        updateReticle();
    }
    if (e.KeyCode == Keys.Down)
    {
        zoomReticle.Location = new Point(zoomReticle.Location.X, zoomReticle.Location.Y + 1);
        e.SuppressKeyPress = true;
        updateReticle();
    }
}

The MessageBox was there for debugging, it never shows up no matter what key is pressed, the pictureBox doesn't move either. I've used this method for detecting keys and it's always worked fine, I have no idea why it doesn't work now sadboihours
Was this page helpful?