简体   繁体   中英

How can i select drawn rectangle and clear it in Panel?

if i draw some rectangles in panel , how can i select one of them and delete it. My code here i have write it inside panel_OnClick event :

g = panel1.CreateGraphics();
Pen p = new Pen(Color.Black);
p.Width = 2;
g.DrawRectangle(p, e.X, e.Y, 100, 60);
p.Dispose();
g.Dispose();

Rectangle will have a Region .
You will need to subscribe to one of the following: MouseClick , MouseDown , MouseUp .

// assuming you keep a reference of the rectangle

void OnMouseClick(object sender, MouseEventArgs e) {
   if(myRect.Region.IsVisible(e.Location) {
      // perform action on myRect ... 
      // have window Invalidate(myRect)
      // Refresh() the invalidated area.
   }   

}

This snippet assumes that no Rectangles overlap. You can also create a GraphicsPath from the points of the Rectangle and then from that path, I believe you can create a Region that enables the actual lines of the rectangle to be selected.

Update per comment

Region
GraphicsPath

I checked and I didn't see the Region property for Rectangle . So, to create the Region do the following:

var gPath = new GraphicsPath();
gPath.AddRectangle(rectangle);

var region = new Region(gPath);  

Drawing on the panel is like drawing on a piece of paper - they are etched in and are no longer a rectangle, but a collection of pixels. Even though you could draw a rectangle over the one you want to clear using the background color, you won't be "removing the rectangle", you'll just draw a rectangle over the existing one.

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