Change all MenuItems ForeColor at once when click a button

90 views Asked by At

My program themes

I already came with this question, but the answer was not what I expected...


As you can see in the image above, I have two themes (Light & Dark). The "Light" theme is working well, but when I click in the "Dark" theme the menuItems from the dropdown still the same, with the same ForeColor(Black). I wonder if it has some way, that when I click the "Dark" button, it changes every item ForeColor to White without the trouble of changing one by one.

private void darkToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.BackColor = Color.FromArgb(30,30,30);
    lblTvalue.Text = "0";
    Application.DoEvents();
    menuStrip.ForeColor = Color.FromArgb(225,225,225); //<- I want a code like this
    menuStrip.Renderer = new MyRendererBlack();
}

Some people told me to do one by one like:

private void darkToolStripMenuItem_Click(object sender, EventArgs e)
{
    this.BackColor = Color.FromArgb(30,30,30);
    menuStrip.ForeColor = Color.FromArgb(225,225,225);
    themeToolStripMenuItem.ForeColor = Color.FromArgb(225,225,225);
    lightToolStripMenuItem.ForeColor = Color.FromArgb(225,225,225);
    darkToolStripMenuItem.ForeColor = Color.FromArgb(225,225,225);
    testToolStripMenuItem.ForeColor = Color.FromArgb(225,225,225);
}

But, what if I want to add a new item? I will have to do this all the time? Is there is a simple way that takes the property of the ToolStripMenuItem and make everything white? Something like:

ToolStripMenuItem.ForeColor = Color.FromArgb(225,225,225);

Please, help.

1

There are 1 answers

1
Amin Mirzaei On

See, in order to change the forecolor of the items, you need to use loops, especially the foreach loop, which I wrote the following code for you, I hope it helps.

public System.Drawing.Color MenuForeColor
{
  get { return this.menuForeColor; }
  set
  {
    this.menuForeColor = value;
    foreach (ToolStripMenuItem item in this.Items.OfType<ToolStripMenuItem>())
    {
      item.ForeColor = value;
      foreach (ToolStripMenuItem drop1 in item.DropDownItems.OfType<ToolStripMenuItem>())
      {
        drop1.ForeColor = value;
        foreach (ToolStripMenuItem drop2 in drop1.DropDownItems.OfType<ToolStripMenuItem>())
        {
          drop2.ForeColor = value;
        }
      }
    }
  }
}