Search code examples
c#winformsright-clickcontextmenustrip

How can I programmatically add a Context Menu Strip to all controls on a win Form in c#


I have a Context Menu Strip (contextColorOptions) that allows the ability to change the background color and forecolor of whatever sourcecontrol accessed the Context Menu Strip.

    private void backgroundColorToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (colorDialog1.ShowDialog() == DialogResult.OK)
        {
            contextColorOptions.SourceControl.BackColor = colorDialog1.Color;
        }
    }

    private void textColorToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (colorDialog1.ShowDialog() == DialogResult.OK)
        {
            contextColorOptions.SourceControl.ForeColor = colorDialog1.Color;
        }
    }

    private void resetColorsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        contextColorOptions.SourceControl.BackColor = DefaultBackColor;
        contextColorOptions.SourceControl.ForeColor = DefaultForeColor;
    }

I want to be able to assign every control in my form to have the same context menu strip.

I tried this:

        foreach (Control cntrl in this.Controls)
        {
            cntrl.ContextMenuStrip = contextColorOptions;
        }

But that didn't seem to work. does anyone have any ideas? Thank you in advance!


Solution

  • Caution not all controls have the same properties, and you can call in the same way. You have to check before if that control have a property name called backcolor, forecolor or contextmenustrip. The key is query the type of the control and change color on backgrounds and panels, and set the transparent color for all inside.

    There is other simple ways but this works:

    foreach (Control cntrl in this.Controls)
            {
                if (cntrl.getType() == "System.Windows.Forms.Form")
                      cntrl.ContextMenuStrip = contextColorOptions;
            }
    

    Hope this help!!. If you whant to get the properties of a control to check if the control have the property you want, you have to use something like this:

    var controlType = control.GetType();
            var property = controlType.GetProperty("The property you are looking for", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
    

    if property != null you got it :)