Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.ToString() == "Left")
                pictureBox1.Location = new Point(pictureBox1.Location.X - 20, pictureBox1.Location.Y);
            else if (e.KeyCode.ToString() == "Right")
                pictureBox1.Location = new Point(pictureBox1.Location.X + 20, pictureBox1.Location.Y);
            else if (e.KeyCode.ToString() == "Up")
                pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y - 20);
            else if (e.KeyCode.ToString() == "Down")
                pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y + 20);
        }
Posted
Updated 17-Jul-11 22:26pm
v2
Comments
Аslam Iqbal 18-Jul-11 4:28am    
what is you problem? Did you set the form property keypreview=true?
Valery Possoz 18-Jul-11 4:36am    
Hello,

You could have used "if (e.KeyCode == Keys.Left)" but otherwise it is fine, this code is correct, the problem must be somewhere else.

Valery.

1 solution

First off, that isn't VB, or VB.NET. It's C#...

Secondly, don't use ToString and string comparison:
private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Left)
                pictureBox1.Location = new Point(pictureBox1.Location.X - 20, pictureBox1.Location.Y);
            else if (e.KeyCode == Keys.Right)
                pictureBox1.Location = new Point(pictureBox1.Location.X + 20, pictureBox1.Location.Y);
            else if (e.KeyCode == Keys.Up)
                pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y - 20);
            else if (e.KeyCode == Keys.Down)
                pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y + 20);
        }

Third, the form probably won't get the KeyUp event anyway: If there is any control on your form which can take keyboard input, it will get the focus, and will get the keys instead (since it is supposed to handle keys, and the form isn't) - so will will need to handle this in the various controls, rather than at the form.

Fourth, it is more normal to handle KeyDown, or KeyPress, rather than KeyUp anyway...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900