Reputation: 7348
How to auto save all properties winforms when closed and auto load all properties winforms when load ? C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace SControl
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < Controls.Count; i++)
{
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Controls[i]));
Stream stream = File.Open("test.xml", FileMode.Create);
x.Serialize(stream, Controls[i]);
}
}
}
}
Upvotes: 3
Views: 21113
Reputation: 166476
Your question is a little unclear, but
If you require saving/loading of the Form Layout have a look at
Windows Forms User Settings in C#
If you require saving/loading an object/class have a look at
Load and save objects to XML using serialization
EDIT:
This will show you how to persist certain settings for form properties.
Save and Restore Setings of a .NET Form using XML
Also have a look at The Application Automation Layer - Using XML To Dynamically Generate GUI Elements--Forms And Controls
All these will guide you in the direction you need to go.
I think the main objective here is
Upvotes: 6
Reputation: 95654
The process of turning objects like forms into something that could be saved is called serialization. Unfortunately I don't think there's an out-of-box way to serialize forms in WinForm. I did find How to Clone/Serialize/Copy & Paste a Windows Forms Control, and since forms are also controls, you might be able to serialize the properties using the code.
Upvotes: 0
Reputation: 25810
You have to manually code which properties to be saved.
A convenient method is to svae these personalized settings to Windows Forms Application Settings.
Sample code snippet:
//save the winform position and size upon closing
private void Form1_FormClosed(
object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.FormPosition = this.Location;
Properties.Settings.Default.FormSize = this.Size;
Properties.Settings.Default.Save();
}
//load the winform position and size upon loading
private void Form1_Load(object sender, EventArgs e)
{
this.Size = Properties.Settings.Default.FormSize;
this.Location = Properties.Settings.Default.FormPosition;
}
More references:
Upvotes: 0
Reputation: 8374
I'm not aware of any automatic method built into the Form
base class, but adding it yourself isn't hard.
You could tap the window load and close events to cache off all relevant properties to a backing store and then reload them later.
Register an event handler to the Form.Load
and Form.Closing
event handlers. When Form.Closing
occurs, save the forms state to a file or database. When Form.Load
occurs, check to see if a saved state is present and if so, reload the from from the saved state.
Upvotes: 0