简体   繁体   中英

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.

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;
     }
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM