C # How to create code to return a form to its default properties with a button click event?

Using Visual C # 2008 express edition, I am trying to create a button in my form to return the form to its default properties, such as size, back side, etc. Does anyone have examples of how I will do this?

+3
source share
4 answers

The easiest way is to simply create a new instance of the form and close the old one. This requires a little operation, if this is the main form of your application, and closing the program will stop working. Start by opening Program.cs and edit it to look 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;
}

ApplicationContext , Form1. , 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();
    }
+1

, .

, :

class DefaultFormInfo
{
    int Width { get; set; }
    int Height { get; set; }
}

:

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);
    }
}
+1

, " ":

// 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 on your button: reset the default values:

// 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 several more powerful ways to do this using the Visual Studio Settings feature (at design time and runtime): check them out:

How to create application settings using the constructor

Application Settings Overview

How to write user settings at runtime using C #

How to: Read settings at runtime with C #

+1
source

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


All Articles