You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm:点击按钮无需关闭窗体恢复控件初始值(.NET 4.0)

WinForm控件一键恢复初始值最简实现

需求说明

WinForm窗体加载前已通过配置文件将控件初始值读取到Settings类,启动流程正常。当控件值发生变化时会显示Cancel按钮,点击该按钮时无需关闭窗体,直接将所有控件恢复至初始值(如示例中的MYBox),无需重新加载窗体。

修改后的完整代码

public class Settings
{
    public static string MYPathFile_M = "";
}

public class MYClass
{
    [STAThread]
    public void main()
    {
        if(!fileExists())  // 验证配置文件存在并读取到变量
        {
            Application.EnableVisualStyles();
            Application.Run(new MYFORM_FORM());
        }
    }

    public bool fileExists()  // 简化代码示例
    {
        // 实际逻辑:判断文件是否存在,读取配置并赋值到Settings类变量
        return true;
    }
}

public class MYFORM_FORM : Form
{
    public string result = null;
    // 将MYBox改为窗体成员变量,方便在事件方法中访问
    private RichTextBox MYBox;

    public MYFORM_FORM()
    {
        // 窗体基础设置
        this.ClientSize = new Size(1452, 577);
        this.Font = new Font("Arial", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
        this.Margin = new Padding(2, 4, 2, 4);
        this.FormBorderStyle = FormBorderStyle.FixedDialog;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.ControlBox = false;
        this.StartPosition = FormStartPosition.CenterScreen;
        this.MinimumSize = new Size(this.Width, this.Height);
        this.MaximumSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        int FontSize = 12;
        int ControlSpacing = 15;
        this.FormClosing += new FormClosingEventHandler((sender, e) => MYFORM_FORM_FormClosing(sender, e));
        this.Load += new System.EventHandler((sender, e) => MYFORM_FORM_Load(sender, e));
        this.Name = "MYFORM_FORM";
        this.Text = "My Form Settings";

        // 初始化MYBox
        MYBox = new RichTextBox();
        MYBox.Location = new Point(12, 313);
        MYBox.Name = "MYBox";
        MYBox.ReadOnly = false;
        MYBox.ScrollBars = RichTextBoxScrollBars.Vertical;
        MYBox.ShortcutsEnabled = false;
        MYBox.Size = new System.Drawing.Size(938, 56);
        MYBox.TabIndex = 10;
        MYBox.Text = Settings.MYPathFile_M;  // 从Settings类读取初始值
        this.Controls.Add(MYBox);
        MYBox.BringToFront();

        // 初始化Cancel按钮
        Button Cancel_Button = new Button();
        Cancel_Button.AutoEllipsis = true;
        Cancel_Button.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
        Cancel_Button.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Gray;
        Cancel_Button.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
        Cancel_Button.Location = new Point(1035, 517);
        Cancel_Button.Name = "Cancel_Button";
        Cancel_Button.Text = "CANCEL";
        Cancel_Button.Size = new Size(200, 48);
        Cancel_Button.Visible = false;  // 控件变更时设为可见
        Cancel_Button.TabIndex = 20;
        Cancel_Button.UseVisualStyleBackColor = true;
        Cancel_Button.Click += new EventHandler((sender, e) => Cancel_Button_Clicked(sender, e));
        this.Controls.Add(Cancel_Button);

        Functions.ShowForm(this);
    }
    
    private void Cancel_Button_Clicked(object sender, EventArgs e)
    {
        if(Global.SaveChanges)  // 判断是否有变更
        {
            DialogResult dr = MessageBox.Show("确定要取消所有更改吗?","", MessageBoxButtons.YesNo);
            switch(dr)
            {
                case DialogResult.Yes:
                    this.Controls["Cancel_Button"].Visible = false;
                    // 核心:恢复控件初始值
                    MYBox.Text = Settings.MYPathFile_M;
                    // 重置变更标记
                    Global.SaveChanges = false;
                    break;
                case DialogResult.No:
                    break;
            }
        }
        else { this.Close(); }
    }

    // 补充原代码中缺失的FormClosing和Load方法实现示例
    private void MYFORM_FORM_FormClosing(object sender, FormClosingEventArgs e)
    {
        // 可添加关闭前的逻辑
    }

    private void MYFORM_FORM_Load(object sender, EventArgs e)
    {
        // 可添加加载时的逻辑
    }
}

public class Functions
{
    public static void ShowForm(Form f)
    {
        IntPtr myHandle = f.Handle;
        SetForegroundWindow(myHandle.ToInt32());
    }

    [DllImport("User32.dll")]
    public static extern Int32 SetForegroundWindow(int hWnd);
}

// 补充原代码中提到的Global类示例
public static class Global
{
    public static bool SaveChanges = false;
}

关键实现说明

  1. 控件变量调整:将构造函数中局部定义的MYBox改为窗体的私有成员变量,这样在Cancel按钮的点击事件中可以直接访问并修改其值。
  2. 恢复初始值:在确认取消更改后,直接从Settings类中读取初始值赋值给对应控件——因为初始值已经存储在Settings中,无需额外保存控件初始状态,这是最简的实现方式。
  3. 状态重置:将Global.SaveChanges设为false,确保后续状态判断正确,同时隐藏Cancel按钮。

如果有更多类型的控件(如TextBox、CheckBox、ComboBox等),只需要在Cancel事件中添加对应的赋值逻辑即可,例如:

  • CheckBox:myCheckBox.Checked = Settings.MyCheckboxValue;
  • ComboBox:myComboBox.SelectedValue = Settings.MyComboValue;

内容的提问来源于stack exchange,提问作者Aricider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:35:18