C # how to programmatically create a replica of my form?

I am using winforms with visual studio 2008.

I would like to create an exact copy of my form with controls and all the events and all the same code as mine.

can this be done at runtime? how would i do that?

There should not be some class solution, for example:

Form form2 = new Form();
form2 = form1 ???
+3
source share
2 answers

Just create another instance of the same class. Use the actual class name instead of the base class Form.

Form form2 = new Form1();
form2.Show();
+5
source

, .:) .

, ... ? I.E., , ( ) ? ... , ,

, , ICloneable, , Clone(). , :

public object Clone() {

    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();
    formatter.Serialize(stream, this);
    stream.Seek(0, SeekOrigin.Begin);

    return (MyForm) formatter.Deserialize(stream);

}

:

MyForm form2 = form1.Clone() as MyForm;
if (form2 != null) {
    // yahoo!
}

* *
, SO, . !


* *
, ... , . .

, ISerializable GetObjectData(). GetObjectData (, ), . . :

public partial class MyForm : Form, ISerializable {

    public MyForm() {}

    public MyForm(SerializationInfo info, StreamingContext context) : base() {

        foreach (Control control in Controls) {
            control.Text = info.GetString(control.Name);
        }

    }

    public void GetObjectData(SerializationInfo info, StreamingContext context) {

        foreach (Control control in Controls) {
            info.AddValue(control.Name, control.Text);
        }

    }

}

, , SerializationInfo . .

+1

Source: https://habr.com/ru/post/1773324/


All Articles