Hi I have tried to draw an rubberband rectangle on a form using the mouse in C#.
Problems
1) After the mouse release the rectangle disappears. [I want it to stay on the form]
2) I also need to find the coordinates of the four points of the drawn rectangle
3) I also need to erase the rectangle to draw a new one when necessary
Form :
CODE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace rubberbandrectangle
{
public partial class Form1 : Form
{
Boolean bHaveMouse;
Point ptOriginal = new Point();
Point ptLast = new Point();
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
bHaveMouse = true;
ptOriginal.X = e.X;
ptOriginal.Y = e.Y;
ptLast.X = -1;
ptLast.Y = -1;
}
private void MyDrawReversibleRectangle(Point p1, Point p2)
{
Rectangle rc = new Rectangle();
p1 = PointToScreen(p1);
p2 = PointToScreen(p2);
if (p1.X < p2.X)
{
rc.X = p1.X;
rc.Width = p2.X - p1.X;
}
else
{
rc.X = p2.X;
rc.Width = p1.X - p2.X;
}
if (p1.Y < p2.Y)
{
rc.Y = p1.Y;
rc.Height = p2.Y - p1.Y;
}
else
{
rc.Y = p2.Y;
rc.Height = p1.Y - p2.Y;
}
ControlPaint.DrawReversibleFrame(rc,
Color.Red, FrameStyle.Dashed);
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
bHaveMouse = false;
if (ptLast.X != -1)
{
Point ptCurrent = new Point(e.X, e.Y);
MyDrawReversibleRectangle(ptOriginal, ptLast);
}
ptLast.X = -1;
ptLast.Y = -1;
ptOriginal.X = -1;
ptOriginal.Y = -1;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
Point ptCurrent = new Point(e.X, e.Y);
if (bHaveMouse)
{
if (ptLast.X != -1)
{
MyDrawReversibleRectangle(ptOriginal, ptLast);
}
ptLast = ptCurrent;
MyDrawReversibleRectangle(ptOriginal, ptCurrent);
}
}
private void Form1_Load(object sender, EventArgs e)
{
MouseDown += new MouseEventHandler(Form1_MouseDown);
MouseUp += new MouseEventHandler(Form1_MouseUp);
MouseMove += new MouseEventHandler(Form1_MouseMove);
bHaveMouse = false;
}
}
}
Thanks for reading