如何在运行时在面板上创建按钮的快捷方式?

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

我有一个包含很多按钮的面板(右面板)。我想在运行时动态地将所选按钮的快捷方式添加到另一个具有相同属性和事件的面板(左面板)。 按钮有很多属性,如图像、文本、背景颜色、前景色……等等

此外,按钮将在主面板中打开新表单:

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();
}

如何在左侧面板上创建快捷方式?

像这样创建 class 按钮

按钮 leftpannelbutton = new Button(); 左面板按钮 = button1.Clone();

现在 leftpannelbutton 等于 button1。现在只需将其添加到您的表单中即可。

在下方查找(反射)

public static class ControlExtensions
{
    public static T Clone<T>(this T controlToClone) 
        where T : Control
    {
        PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        T instance = Activator.CreateInstance<T>();

        foreach (PropertyInfo propInfo in controlProperties)
        {
            if (propInfo.CanWrite)
            {
                if(propInfo.Name != "WindowTarget")
                    propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
            }
        }

        return instance;
    }
}

您可以创建一个克隆方法,它接受一个按钮作为输入并根据输入按钮的属性创建另一个按钮,还可以处理克隆按钮的点击事件,只需调用输入按钮的 PerformClick 方法:

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;
}

那么你可以这样使用:

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

另外,最好不要使用面板,而是使用 FlowLayoutPanelTableLayoutPanel,这样您就不需要自己处理位置和布局。

注意: 如果它是动态的 UI 并且用户可以重新排序命令按钮或创建您所谓的快捷方式,那么下一步您可能需要存储面板的状态,以便能够在应用程序关闭后的下一次加载应用程序时重新加载按钮。在这种情况下,最好考虑像命令模式这样的模式。然后你可以将你的命令设置为 类。然后你可以说哪个按钮在 运行 时对 运行 哪个命令负责,你可以简单地使用它们的名称存储按钮和命令之间的关系。