简体   繁体   中英

How do I know that picturebox has child controls

I made a little game with c# , but there was a problem. I put a Label in the PictureBox , but I don't know how to tell that there's a Label in the PictureBox .

pbArray[x,y].Controls == label; // ???

Let's put the question in other words:

If there's Any Label within the picture box's Controls ?

We can asnwer it with an easy Linq :

 using System.Linq;

 ...

 bool hasLabel = pbArray[x,y]
   .Controls
   .OfType<Label>()
   .Any();  

However, we can put the question in a different way:

Do we have Any Label which overlaps (ie just painted over or under the picture box; not necessary within picture box's Controls ) the picture box?

In this case we have to implement more code:

private static bool AreOverlapped(Rectangle left, Rectangle right) {
  //TODO: put relevant code here
}

...

Rectangle boxRect = new Rectangle(
  pbArray[x,y].Parent.PointToScreen(pbArray[x,y].Location),
  pbArray[x,y].Size);

bool hasOverlappedLabel = this
  .Controls        // <- Labels that are directly on the form only  
  .OfType<Label>() 
  .Select(lbl => new Rectangle(
     lbl.Parent.PointToScreen(lbl.Location),
     lbl.Size
   ))
  .Any(rect => AreOverlapped(rect, boxRect));

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