Using Visual C# 2008 express edition, I am trying to create a button on my form to set the form back to default properties, such as size, backcolor, etc... anybody have any examples on how I would do this?
views:
174answers:
4For each property info you can get DefaultValueAttribute and set needed Property to its value.
You cannot do this without saving the original state somewhere.
Just create some class that holds the default info:
class DefaultFormInfo
{
int Width { get; set; }
int Height { get; set; }
}
Then use some reflection:
static DefaultFormInfo FormInfo = new DefaultFormInfo();
void FillDefaults()
{
foreach (PropertyInfo pinf in FormInfo.GetType().GetProperties())
{
pinf.SetValue(FormInfo, this.GetType().GetProperty(pinf.Name).GetValue(this, null), null);
}
}
void Restore()
{
foreach (PropertyInfo pinf in FormInfo.GetType().GetProperties())
{
this.GetType().GetProperty(pinf.Name).SetValue(this, pinf.GetValue(FormInfo, null), null);
}
}
By far the simplest way is to just create a new instance of the form and close the old one. That requires a little bit of surgery if this is the main form of your app, closing it would terminate the program. Start by opening Program.cs and edit it so it looks like this:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppContext = new ApplicationContext();
AppContext.MainForm = new Form1();
Application.Run(AppContext);
}
public static ApplicationContext AppContext;
}
The ApplicationContext variable now controls the lifetime of the app, instead of the Form1 instance. You can recreate the form with code like this in Form1:
private void button1_Click(object sender, EventArgs e) {
Form1 frm = new Form1();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size;
Program.AppContext.MainForm = frm;
frm.Show();
this.Close();
}
The simplest solution might be to define some Form level variables, and record the default values in an Event like the Form Load event :
// form scoped variables
private Color defaultBackColor;
private Rectangle defaultBounds;
private FormWindowState defaultFormWindowState;
// save the Form default Color, Bounds, FormWindowState
private void Form1_Load(object sender, EventArgs e)
{
defaultBackColor = this.BackColor;
defaultBounds = this.Bounds;
defaultFormWindowState = this.WindowState;
}
Then in the Click Event of your button : reset the defaults :
// restore the defaults on Button click
private void btn_FormReset_Click(object sender, EventArgs e)
{
this.WindowState = defaultFormWindowState;
this.Bounds = defaultBounds;
this.BackColor = defaultBackColor;
}
There are some more powerful ways of doing this involving using the 'Settings feature of Visual Studio (at Design Time and Run-Time) : check them out at :
How to: Create Application Settings Using the Designer