Click here to Skip to main content
15,939,065 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
In a C# form with one picturebox and one button.
by clicking the button, picture box should move from one edge of the form to another edge around the form?

Please provide simple code if possible

What I have tried:

private void timer1_Tick(object sender, EventArgs e)
int x = _random.Next(1, 2);
int y = _random.Next(1, 2);

pictureBox1.Left += x;

if (pictureBox1.Location = new Point(180, 0))
pictureBox1.Top += y;
else if (pictureBox1.Location = new Point(180, 160)
pictureBox1.Left += -x;

I've failed in all my attempts. #feelinghopeless
Updated 24-May-17 4:48am
Dave Kreskowiak 24-May-17 10:16am    
I wonder what that Location or Top and Left properties that every control has are for...
Member 13200081 24-May-17 10:31am    
i've tried using

_random = new Random(); // declared random value assigned to _random
pictureBox1.Location = new Point(0, 0); // start postion of picture box
int x = _random.Next(0, 2); // move value of x will always be 1
pictureBox1.Left += x;

my coding didn't work out because i could not bound picturebox to form, that been number 1 and it changing direction as soon as it reaches the end of form as number 2.
Dave Kreskowiak 24-May-17 10:37am    
It would have been nice to put this information in your original post. You never mentioned anything about trying any code nor having any problems with the code you've written.
Member 13200081 24-May-17 10:49am    
iv done so, now the whole world knows i cant code #hides :-)

1 solution

Use a Timer, and start it in the button.
In the Tick event, change the Top and Left properties of the PictureBox a small amount - the more the change, the "jumpier" the image movement. Remember to check for the edges of it's container: Top vs 0 when going up, Left vs 0 when going left, Top + Height vs Height when going down, Left + Width vs Width when going right.

But this is your homework, so I'll give you no code!
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