繁体   English   中英

C#如何使用按钮单击事件创建代码以将表单设置回默认属性?

[英]C# How do I create code to set a form back to default properties, with a button click event?

使用Visual C#2008快速版,我试图在我的表单上创建一个按钮,将表单设置回默认属性,如大小,背景颜色等等......任何人都有关于我如何做这个的任何例子?

对于每个属性信息,您可以获取DefaultValueAttribute并将所需的Property设置为其值。

如果不在某处保存原始状态,则无法执行此操作。

只需创建一个包含默认信息的类:

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

到目前为止,最简单的方法是创建表单的新实例并关闭旧表单。 如果这是你的应用程序的主要形式,这需要一些手术,关闭它将终止程序。 首先打开Program.cs并编辑它,看起来像这样:

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();
    }

最简单的解决方案可能是定义一些表单级别变量,并在事件中记录默认值,如Form Load事件:

// 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;
}

然后在按钮的Click事件中:重置默认值:

// restore the defaults on Button click
private void btn_FormReset_Click(object sender, EventArgs e)
{
    this.WindowState = defaultFormWindowState;
    this.Bounds = defaultBounds;
    this.BackColor = defaultBackColor;
}

有一些更强大的方法可以实现这一点,包括使用Visual Studio的“设置”功能(在设计时和运行时):在以下位置查看它们:

如何:使用Designer创建应用程序设置

应用程序设置概述

如何:使用C#在运行时编写用户设置

如何:使用C#在运行时读取设置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM