C#:在 FlowLayoutPanel 中使用 backgroundworker 更改我的矩形的颜色

C#: change the color of my rectangle with backgroundworker in a FlowLayoutPanel

我尝试让我的软件根据 IP 地址显示绿色或红色方块,无论它是否有效,当然所有这些都在 FlowLayoutPanel (ca_imp) 中并且在我创建一个方块数字之前根据我将在第二个 FlowLayoutPanel(listeImprimantes) 中添加的地址数量。

private void RdFichierXml()
        {
            int i = 0;
            XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object
            xmlDoc.Load("imprimante.xml"); // Load the XML document from the specified file

            // Get elements
            girlNom = xmlDoc.GetElementsByTagName("nom");
            girlIp = xmlDoc.GetElementsByTagName("ip");
            girlRemarques = xmlDoc.GetElementsByTagName("remarques");

            // Display the results
            for (i = 0; i < girlIp.Count; i++)
            {
                buttons(girlIp[i].InnerText, girlNom[i].InnerText, girlRemarques[i].InnerText);
                buttons1(i, girlIp[i].InnerText);
            }
        }

private void buttons(string ip, string name, string remarque)
        {
            Panel Case = new Panel();
            Case.Font = new System.Drawing.Font("Mont", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            Case.Name = "Case";
            Case.Size = new System.Drawing.Size(234, 49);
            Case.Text = name + "\r\nIP : " + ip + "\r\nREMARQUE : " + remarque + "\r\n"; ;
            Case.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;

            listeImprimantes.Controls.Add(Case);
        }

private void buttons1(int i, string ip)
        {
            Panel Case1 = new Panel();
            Case1.Name = "Case_color" + i;
            Case1.Size = new System.Drawing.Size(16, 49);
            Case1.TabIndex = i;
            Case1.BringToFront();
            Case1.BackColor = Color.Gray;
            
            ca_imp.Controls.Add(Case1);
        }


 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < girlIp.Count; i++)
            {
               /*if (check(girlIp[i].InnerText) == 1) //check is a funtion that return 1 if the ip is valid or 0 if not
              {
                  ?.BackColor = Color.Green;
              }
              else if (check(girlIp[i].InnerText) == 0)
              {
                  ?.BackColor = Color.Red;
              }*/
            }
        }

我可以得到一些帮助来改变 backgroundWorker 或其他颜色而不冻结我的 window 请...

有很多方法可以做到这一点,这里是一个:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < girlIp.Count; i++)
    {
        int result = check(girlIp[i].InnerText);

        String cltName = "Case_color" + i;
        Panel pnl = this.Controls.Find(ctlName, true).FirstOrDefault() as Panel;
        if (pnl != null)
        {
            pnl.Invoke((MethodInvoker)delegate () {
                pnl.BackColor = (result == 1) ? Color.Green : Color.Red;
            });
        }
    }
}