Shooting from the hip, serialize the form and deserialize it into the second variable. : ) I'll try to look into this and come up with more of an answer.
Some things to watch out for... do you want a shallow or deep copy? I.E., if the form has a reference to an object, do you want to copy the reference (so both forms are pointing to the same object), or make a copy of that object, also? You have to be careful... there's no guarantee with objects that contain references to other objects which order they will be deserialized
You don't need to, but it's good practice to inherit from ICloneable, which has only one method, Clone()
. Override this method with code similar to the following:
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);
}
To use:
MyForm form2 = form1.Clone() as MyForm;
if (form2 != null) {
// yahoo!
}
* Edit *
There's actually an excellent example here on SO that creates a generic object copier. Very nice!
Deep cloning objects
* Edit *
The problem with serializing the form is that not all the values can really be serialized... they make no sense, e.g. the handles on the individual controls.
To make the form serializable, you will need to implement the ISerializable interface, and implement the proper constructor and GetObjectData() method. In GetObjectData, you will need to enumerate your controls, and store the properties (e.g. Text or Value) that you want to copy. The constructor reads them back out. It looks like this:
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);
}
}
}
The idea is, enumerate the form, put every value into SerializationInfo stream, and pull it back out when you create a new object. This will allow my original code for Cloning to work.