开发者

Key press events in C# -- Moving a PictureBox

开发者 https://www.devze.com 2023-03-05 10:10 出处:网络
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 c

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

0

精彩评论

暂无评论...
验证码 换一张
取 消