简体   繁体   中英

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.

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.

If the problem is the flickering only. You might want to set the Forms double buffer property to true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM