public class Rubberband
{
protected Control parent;
protected Rectangle rect = Rectangle.Empty;
public Rubberband(Control theParent, Point theStartingPoint)
{
parent = theParent;
parent.Capture = true;
Cursor.Clip = parent.RectangleToScreen(parent.ClientRectangle);
rect = new Rectangle(theStartingPoint.X, theStartingPoint.Y, 0, 0);
}
public void End()
{
Cursor.Clip = Rectangle.Empty;
parent.Capture = false;
// erase the rubberband
Draw();
rect = Rectangle.Empty;
}
public void ResizeTo(Point thePoint)
{
// erase the old rubberband
Draw();
// get the new size of the rubberband
rect.Width = thePoint.X - rect.Left;
rect.Height = thePoint.Y - rect.Top;
// draw the new rubberband
Draw();
}
public Rectangle Bounds()
{
// return a normalized rectangle, i.e. a rect
// where (left <= right) and (top <= bottom)
if ( (rect.Left > rect.Right) || (rect.Top > rect.Bottom) )
{
int left = Math.Min(rect.Left, rect.Right);
int right = Math.Max(rect.Left, rect.Right);
int top = Math.Min(rect.Top, rect.Bottom);
int bottom = Math.Max(rect.Top, rect.Bottom);
return Rectangle.FromLTRB(left, top, right, bottom);
}
return rect;
}
// Reversible drawing method
// Calling theis method the first time draws the rubberband.
// Calling it a second time with the same rect erases the rubberband
protected void Draw()
{
Rectangle r = parent.RectangleToScreen(rect);
ControlPaint.DrawReversibleFrame(r, Color.White, FrameStyle.Dashed);
}
}
//---------------------------------------
// BlockOut.cs ?2001 by Charles Petzold
//---------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;
class BlockOut: Form
{
bool bBlocking, bValidBox;
Point ptBeg, ptEnd;
Rectangle rectBox;
public static void Main()
{
Application.Run(new BlockOut());
}
public BlockOut()
{
Text = "Blockout Rectangle with Mouse";
BackColor = SystemColors.Window;
ForeColor = SystemColors.WindowText;
}
protected override void OnMouseDown(MouseEventArgs mea)
{
if (mea.Button == MouseButtons.Left)
{
ptBeg = ptEnd = new Point(mea.X, mea.Y);