bananajunk
bananajunk

Reputation: 97

Key press events in C# -- Moving a PictureBox

I am attempting to move a PictureBox(picUser) up and down via the key press events. I am newer to C# and am able to do this via VB. As such I am confused as to what the problem is with the following code:

    private void picUser_keyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        if (e.KeyCode == Keys.W)
        {
            picUser.Top -= 10;
        }
    }

There is no "error" with the code, the picturebox just doesn't move.

Upvotes: 3

Views: 19392

Answers (2)

Larry
Larry

Reputation: 18031

A PictureBox has no KeyDown event. It has a PreviewKeyDown instead and requires the PictureBox to have the focus.

I would suggest to use the KeyDown of the form that host the PictureBox instead and use the same exact code:

public Form1()
{
     InitializeComponent();
     this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.W)
     {
         picUser.Top -= 10;
     }
}

Upvotes: 6

MusiGenesis
MusiGenesis

Reputation: 75296

It's probably not working because picUser does not have the focus, and thus does not receive any key events.

If picUser has the focus, your code should work. However, a better way is probably to set your form's KeyPreview property to true, and then put your code above into the form's keyDown event (and set e.Handled = true as well, to prevent the key event from being passed on to whichever control does have the focus).

Upvotes: 2

Related Questions