Things You'll Need:
- Microsoft Visual C# 2008 Express (free)
-
Step 1
Note: This article assumes you have installed Microsoft Visual C# 2008 Express Edition. You may download it for free from here: http://www.microsoft.com/express/download/
Open Microsoft Visual C#. Click on "Project..." to the right of Create in the Recent Projects area of the Start Page.
The New Project window will open. Click on "Windows Forms Application", enter a Name, and click OK.
By default, the only form in the project will be called "Form1" and you will be in Design mode for that form. -
Step 2
The form will be displayed in design view. Right-click on the form and select Properties. This will bring up the Properties window.
-
Step 3
In the toolbar for the Properties window, click the button with the lightning bolt icon on it. This will show you the events for the form.
-
Step 4
Double-click the empty cell to the right of the MouseClick event.
-
Step 5
You will now be in the Form1_MouseClick event. But before we can add our code, we must first declare our rectangles.
-
Step 6
Before the line "public Form1()", add the following lines:
private Rectangle RedRectangle = new Rectangle(30, 30, 40, 40);
private Rectangle BlueRectangle = new Rectangle(80, 80, 40, 40);
This will create one rectangle at location (30,30), and another one at location (80,80). -
Step 7
Go back to the Form1_MouseClick and enter the following lines:
RedRectangle.Location = new Point(e.X, e.Y);
this.Refresh();
This sets the location of the RedRectangle to the point clicked on by the user. e.X and e.Y are the pixel locations of the user's mouse click.
We then call the form's Refresh method to repaint the form. -
Step 8
Return to design view by clicking on the tab entitled "Form1.cs [Design]".
-
Step 9
The Properties window should still be active so find the Paint method for Form1 and double-click the empty cell to the right. This will create the Form1_Paint method in code and take you there.
-
Step 10
Add the following lines in the Form1_Paint method:
e.Graphics.DrawRectangle(Pens.Red, RedRectangle);
e.Graphics.DrawRectangle(Pens.Blue, BlueRectangle);
if (RedRectangle.IntersectsWith(BlueRectangle))
{
MessageBox.Show("COLLISION!");
}
This will draw both rectangles on the screen. It will then use the IntersectsWith method of one of the rectangles to see if it collides with the other rectangle. If so, a message is displayed. -
Step 11
Go up to the toolbar and run the program by clicking on the Start Debugging (f5) play button.
NOTE: If you got any kind of error after clicking the play button, you probably made a syntax error when typing the code. Reread the code until you find and correct the error and try again. -
Step 12
Click somewhere on the form and, if you clicked in the right spot, a message will be displayed. This is way too easy!















