Clone Controls – C# (Winform) [duplicate]

Generally speaking you can use reflection to copy the public properties of an object to a new instance.

When dealing with Controls however, you need to be cautious. Some properties, like WindowTarget are meant to be used only by the framework infrastructure; so you need to filter them out.

After filtering work is done, you can write the desired one-liner:

Button button2 = button1.Clone();

Here’s a little code to get you started:

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

Of course, you still need to adjust naming, location etc. Also maybe handle contained controls.

Leave a Comment