Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a picturebox not support keyboard events?

I am currently using Visual Studio, and I don't know if this is a glitch or not, but when I go into the form properties, and show the events, there are two events called KeyDown and KeyUp. Now when I do the same for a PictureBox, it has way less events and no KeyDown and KeyUp events. Does the PictureBox support less events then other things? Is this a glitch?

Screenshot of Form1 properties:

enter image description here

Screenshot of PictureBox1 properties:

enter image description here

like image 727
OneStig Avatar asked Nov 01 '25 16:11

OneStig


2 Answers

As others here have stated, the most appropriate method for capturing keyboard event in this situation is to intercept key events at the Form level, as the PictureBox control is incapable of receiving focus and lacks exposed key events.

To accomplish this, first set the KeyPreview property of the form to true within the designer, or alternatively within the form's constructor:

this.KeyPreview = true;

Then, subscribe to the KeyUp event:

this.KeyUp += MainForm_KeyUp;

Finally, use an event handler similar to as follows to intercept and process key events:

private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.A:
            // Perform some action...
            break;
        case Keys.B:
            // Perform some action...
            break;
        case Keys.End:
            // Perform some action...
            break;

        // etc...

    }
}


If you intend to "consume" the key from within the event handler, you may set the Handled property of the KeyEventArgs object as follows:

e.Handled = true;
like image 129
Lemonseed Avatar answered Nov 04 '25 08:11

Lemonseed


Its not a glitch. Its the way it is. You don't type in PictureBox. If you need to do some task through keys, route it through form only

like image 37
Anup Sharma Avatar answered Nov 04 '25 06:11

Anup Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!