Home > database >  c# all label detect one function-void
c# all label detect one function-void

Time:09-13

I'm going to make a simple maze game in C#. In the picture box, the visual keyboard will go up, down, left and right, there is no problem here.

Going to the starting point when touching the labels with event autosize true. When I have 100 labels, I don't want to write 100 ifs.

If the Picturebox does the following on any label (below);

if (pictureBox1.Right >= label1.Left && pictureBoxl.Bottom >= label1.Top)
{
   if (pictureBox1.Left <= label1.Right && pictureBoxl.Top <= label1.Bottom)
   {
       //pictureBox1 and label1 touching
   }
}

Label1 above will be checked for all labels. this is what i want

How can I do that.

Regards..

CodePudding user response:

You may add all the labels to an array and check them in a for loop:

1.Declare a global array:

Label[] myLabels;
  1. Initialize myLabel array in InitializeComponent:
myLabels= new Label[] {label1, label2, ... };
  1. Check in a for loop:
for(int i = 0; i < myLabels.Length; i  )
{
   if (pictureBox1.Right >= myLabels[i].Left && pictureBoxl.Bottom >= myLabels[i].Top)
   {
      if (pictureBox1.Left <= myLabels[i].Right && pictureBoxl.Top <= myLabels[i].Bottom)
      {
          //pictureBox1 and myLabels[i] touching
          return;
      }
   }
}
  • Related