Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can anyone please help me? I'm trying to make is so that if a pictuebox hits another picrebox something will happen for example i'm using

C#
if (e.KeyCode == Keys.Up)
{
    You.Location = new Point(You.Location.X, You.Location.Y - 5);
}


and the picturebox will go up and when it hits another picurebox that is in the area it will do something,

my idea was

if(picturebox1.location == picruebox2.location)
{
}


and it will do something, but it will have to hit a exact pixel, but that is very hard, i want it so if you hit the picturebbox while moving it will do something, can anyone help?
Posted

1 solution

You need to look at the Rectangle.Contains[^] method. If you are moving the point up, use the TLHC of your moving PictureBox, if down, then use the BLHC. (obviously, if it moves sideways adjust the Left and Right there).

In both cases, use the rectangle from the stationary control.

[edit]Oops! Gave you the wrong link: should have been to Contains(Point) instead of Contains(Rectangle). Corrected - OriginalGriff[/edit]


"I don't understand"

OK, I'll try to explain a little more:
Each Picture box has a Rectangle, which consists of it's Location (the Top Left Hand Corner or TLHC) together with it's Width and Height properties.

Each Rectangle has a method called Contains which has an overload taking a Point.

If you call the Rectangle.Contains Method with the Point as the TLHC of your moving PictureBox, the bool result will be true if the TLHC of your moving PictureBox is inside the rectangle of the stationary one.

You can access the TLHC of a control via it's Location property, and the Rectangle via the Bounds property.

So:
C#
movingPictureBox.Top -= 20;
if (stationaryPictureBox.Bounds.Contains(movingPictureBox.Location))
    {
    MessageBox.Show("Inside");
    }
Does that make a bit more sense?
 
Share this answer
 
v3
Comments
[no name] 5-Feb-11 7:19am    
I don't understand
OriginalGriff 5-Feb-11 8:57am    
Answer updated
[no name] 5-Feb-11 17:55pm    
Yes, yay!
[no name] 5-Feb-11 18:05pm    
I thank you so so much, i understand it, I did as much as i could, i accepted your answer, i rated your answer 5/5
[no name] 5-Feb-11 21:23pm    
Oh yeh I forgot to ask, what if the object isn't stationary? is it possible to get the same effect? because my plan is to have both objects moving

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