Search code examples
c#.netwinformseventspanel

How to create shortcut of a button on a panel at runtime?


I have a panel that contains a lot of buttons(right panel). I want to add a shortcut of selected button to another panel(left panel) with the same properties and events dynamically at runtime. Buttons have so many properties like image, text, backcolor, forecolore, ... etc.

App Design

Also the buttons will open new form inside main panel:

private void butntest_Click(object sender, EventArgs e)
{
    this.main_panel.Controls.Clear();
    Form1 myForm = new Form1();
    myForm.TopLevel = false;
    myForm.AutoScroll = true;
    this.main_panel.Controls.Add(myForm);
    myForm.Show();
}

How Can i create a shortcut on left panel?


Solution

  • You can create a clone method which accepts a button as input and creates another button based on the input button's properties, also handle click event of the cloned button and just call PerformClick method of the input button:

    public Button Clone(Button input)
    {
        var output = new Button();
        output.Text = input.Text;
        // do the same for other properties that you need to clone
        output.Click += (s,e)=>input.PerformClick();
        return output;
    }
    

    Then you can use it this way:

    var btn = Clone(button1);
    panel1.Controls.Add(btn);
    

    Also instead of a panel, it's better to use a FlowLayoutPanel or TableLayoutPanel, so you don't need to handle the location and the layout yourself.

    Note: If it's a dynamic UI and users can reorder command buttons or create whatever you called shortcut, the probably for the next step you may need to store the status of the panel to be able to reload buttons at the next load of the application after the application closed. In this case it's better to consider a pattern like command pattern. Then you can have your commands as classes. The then you can say which button is responsible to run which command at run-time and you can simply store the relation between buttons and commands using their names.