'C# How to Draw a Rubber Band Selection Rectangle on Panel, like one used in Windows Explorer?
I have one Flow Layout Panel with some User Controls in it. I Want to Select these controls using rectangle selection using Mouse,like one used in windows file explorer . I have tried these : https://support.microsoft.com/en-us/kb/314945 But it was very flickering and not useful (I might be wrong,please correct me). Any good examples please.
Solution 1:[1]
Drawing the rubber-band rectangle is done like this:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
panel1.Refresh();
using (Graphics g = panel1.CreateGraphics())
{
Rectangle rect = GetRectangle(mdown, e.Location);
g.DrawRectangle(Pens.Red, rect);
}
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
mdown = e.Location;
}
It uses a helper function:
static public Rectangle GetRectangle(Point p1, Point p2)
{
return new Rectangle(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y),
Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y));
}
I don't get any flicker from it. If you do, maybe you have coded the Paint event, you may want to use a double-buffered Panel:
class DrawPanel : Panel
{
public DrawPanel()
{
DoubleBuffered = true;
}
}
Update: Instead of a Panel, which is a Container control and not really meant to draw onto, you can use a Picturebox or a Label (with Autosize=false); both have the DoubleBuffered property turned on out of the box and support drawing better than Panels do.
Solution 2:[2]
If the problem is the flickering only. You might want to set the Forms double buffer property to true.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alan Baljeu |
| Solution 2 | John Thompson |
