The following code performs what you want to do.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace CodeProject
{
public partial class DynamicRectangles : Form
{
Point current_mouse_position;
Point mouse_down_position;
bool drawing = false;
List < Rectangle > rectangles = new List < Rectangle > ( );
public DynamicRectangles ( )
{
InitializeComponent ( );
}
private Rectangle current_rectangle ( )
{
return new Rectangle(
Math.Min ( mouse_down_position.X,
current_mouse_position.X ),
Math.Min ( mouse_down_position.Y,
current_mouse_position.Y ),
Math.Abs ( mouse_down_position.X -
current_mouse_position.X ),
Math.Abs ( mouse_down_position.Y -
current_mouse_position.Y ) );
}
protected override void OnMouseDown ( MouseEventArgs e )
{
base.OnMouseDown ( e );
drawing = true;
current_mouse_position = e.Location;
mouse_down_position = e.Location;
}
protected override void OnMouseMove ( MouseEventArgs e )
{
base.OnMouseMove ( e );
current_mouse_position = e.Location;
if ( drawing )
{
Invalidate ( );
}
}
protected override void OnMouseUp ( MouseEventArgs e )
{
Rectangle rectangle;
base.OnMouseUp ( e );
drawing = false;
rectangle = current_rectangle ( );
if ( ( rectangle.Width > 0 ) && ( rectangle.Height > 0 ) )
{
rectangles.Add ( rectangle );
}
Invalidate ( );
}
protected override void OnPaint ( PaintEventArgs e )
{
base.OnPaint ( e );
if ( rectangles.Count > 0 )
{
e.Graphics.DrawRectangles ( new Pen ( Color.Black ),
rectangles.ToArray ( ) );
}
if ( drawing )
{
e.Graphics.DrawRectangle ( new Pen ( Color.Red ),
current_rectangle ( ) );
}
}
}
}
I have a couple of observations about your code.
1. From MSDN
The On... methods allow derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
I suggest that you use the On... form of event handler declaration. All you need to enter is
protected override in your code and Intellisence will provide you with a list from which you can choose what you want.
2. I am ignoring the canevas [sic] variable.
3. I am ignoring the event handler rectangleShape1_Click.
Hope that helps.
Gus