在C#中使用Form類保存和加載的常用技巧包括:
// 保存Form對象到文件
using (FileStream fs = new FileStream("form.dat", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, this);
}
// 加載Form對象
using (FileStream fs = new FileStream("form.dat", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
Form form = (Form)bf.Deserialize(fs);
form.Show();
}
// 保存Form對象的屬性
Properties.Settings.Default.FormLocation = this.Location;
Properties.Settings.Default.FormSize = this.Size;
Properties.Settings.Default.Save();
// 加載Form對象的屬性
this.Location = Properties.Settings.Default.FormLocation;
this.Size = Properties.Settings.Default.FormSize;
// 保存Form對象到XML文件
XmlSerializer serializer = new XmlSerializer(typeof(Form));
using (TextWriter writer = new StreamWriter("form.xml"))
{
serializer.Serialize(writer, this);
}
// 加載Form對象
XmlSerializer serializer = new XmlSerializer(typeof(Form));
using (TextReader reader = new StreamReader("form.xml"))
{
Form form = (Form)serializer.Deserialize(reader);
form.Show();
}
這些是常用的保存和加載Form對象的技差,根據具體需求可以選擇適合自己的方法進行實現。