Search code examples
c#winformsbuttoncontextmenustrip

Adding function to items in contextmenustrip Windows Forms


I am creating dynamically buttons in windows forms by using the code below. I want to have a context menu with different options pop up when a button is being right clicked. I made the context menu strp and it shows up but i cant figure out how to make the different options perform the functions i have written for them. Any idea how i can connect the items to their functions ?

void AddButton(Shape s){
            Button b = new Button();
            b.Text = s.name;
            b.Width = sceneItemsList.Width-6;
            b.TabStop = false;
            b.FlatStyle = FlatStyle.Flat;
            b.BackColor = Color.LightGray;
            b.FlatAppearance.BorderColor = Color.Black;
            ContextMenuStrip cm = new ContextMenuStrip();
            cm.Items.Add("Deselect");
            cm.Items.Add("Edit");
            if (s is GroupShape)
            {
                cm.Items.Add("Ungroup");
            }
            cm.Items.Add("Delete");
            b.ContextMenuStrip = cm;
}

Solution

  • Figured it out! This is my code if anyone else is struggling with this. Basically you make a loop that goes through all the opptions and adds a click eventhadler

        cm.Items[0].Click += (sender, e) => {
            Console.WriteLine("ok");
        };