C#如何创建代码以通过单击按钮事件将表单设置回默认属性? [英] C# How do I create code to set a form back to default properties, with a button click event?

查看:69
本文介绍了C#如何创建代码以通过单击按钮事件将表单设置回默认属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Visual C#2008 Express Edition,我试图在表单上创建一个按钮,以将表单设置回默认属性,例如大小,背景色等。有人有关于如何执行此操作的示例吗?

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?

推荐答案

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

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

ApplicationContext变量现在控制应用程序的生存期,而不是Form1实例。您可以在Form1中使用以下代码重新创建表单:

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

这篇关于C#如何创建代码以通过单击按钮事件将表单设置回默认属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆