| Language: | C# |
| Category: | Desktop |
| Date: | 2008-09-30 |
| Author: | Michael Flenov |
Many kind of software has to use a rubber band rectangle. The rubber band is a rectangle that tracks with mouse cursor while user hold the mouse button and move it to select something or to move/resize controls. To draw the rubber band rectangle we used to draw rectangle using raster operations (XOR) drawing in GDI. To draw rubber band you had to draw a rectangle using ROP2_XORPEN. To erase the rectangle you had to draw the same rectangle and all lines would be disappeared.
The new graphic interface GDI+ does not implement raster operations. The .NET framework does not implement the old GDI functions. The System.Drawing methods are based on GDI+. What can we do to draw rubber band in the .NET Framework? We can use the platform invocation to access to the old functions but it is the worst technique. Do not use the invocation in such a case. Use a static method DrawReversibleFrame() from ControlPaint like in the example below (it is a small part of one of my project):
public class YourClass
{
Point dragPoint;
bool dragging = false;
void DrawDraggingShape()
{
Point startPont = mapPanel.PointToScreen(dragPoint);
ControlPaint.DrawReversibleFrame(new Rectangle(startPont, Size),
Color.Red, FrameStyle.Dashed);
}
private void mapPanel_MouseDown(object sender, MouseEventArgs e)
{
dragging = true;
dragPoint = e.Location;
DrawDraggingShape();
}
private void mapPanel_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
DrawDraggingShape();
dragPoint = e.Location;
DrawDraggingShape();
}
}
private void mapPanel_MouseUp(object sender, MouseEventArgs e)
{
if (dragging)
{
dragging = false;
DrawDraggingShape();
}
}
}
The rubber band appear when you draw the rectangle using the DrawReversibleFrame methods the first time. To erase the rectangle you have to use the DrawReversibleFrame method agein with the same coordinates.