Today we will see how to draw a rubber band rectangle like Explorer does. in C#. You can easily do the same in VB.NET also.
It was a tough task assigned by my project manager. But I have achieved it.
Steps:
- Create a Windows Form application named as RubberBandRectangle.
- Give Form name as frmMain
- Paste the following code in your frmMain.cs file
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace RubberBandRectangle
{
///
/// Class to simulate Rubber Band rectangle
///
///
public partial class frmMain : Form
{
#region Declaration
private Point MouseDownPosition { get; set; }
private Point CurrentMousePos { get; set; }
Color selectionColor;
Brush selectionBrush;
Color frameColor;
Pen framePen;
#endregion
#region Constructor
public frmMain()
{
InitializeComponent();
this.MouseDownPosition = Point.Empty;
DoubleBuffered = true;
this.BackColor = Color.White;
this.selectionColor = Color.FromArgb(200, 0xE8, 0xED, 0xF5);
this.selectionBrush = new SolidBrush(selectionColor);
this.frameColor = Color.FromArgb(0x33, 0x5E, 0xA8);
this.framePen = new Pen(frameColor);
}
#endregion
#region FormEvents
///
/// MouseMove event
///
///
///
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.Button == MouseButtons.Left && MouseDownPosition != Point.Empty)
Invalidate();
}
///
/// OnPaint Event
///
///
///
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
if (MouseDownPosition != Point.Empty)
{
CurrentMousePos = this.PointToClient(MousePosition);
Rectangle selectedRect = new Rectangle(
Math.Min(MouseDownPosition.X, CurrentMousePos.X),
Math.Min(MouseDownPosition.Y, CurrentMousePos.Y),
Math.Abs(CurrentMousePos.X - MouseDownPosition.X),
Math.Abs(CurrentMousePos.Y - MouseDownPosition.Y));
e.Graphics.FillRectangle(selectionBrush, selectedRect);
e.Graphics.DrawRectangle(framePen, selectedRect);
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
///
/// OnMouseDown Event
///
///
///
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (e.Button == MouseButtons.Left)
MouseDownPosition = e.Location;
}
///
/// OnMouseUp Event
///
///
///
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
MouseDownPosition = Point.Empty;
Invalidate();
}
#endregion
#region Functions
#endregion
}
}
Compile and Run..... fill beauty of .NET.
Keep Smiling.
Mahesh Bagul
Nice one...
ReplyDeleteThanks, It help me...
ReplyDeleteI am looking for the same one.. thanks..
ReplyDeleteThanks
ReplyDelete