C# Winform 程序实现自动保存和恢复界面状态

本文将介绍如何使用 C# 编写一个 Winform 程序,实现自动保存界面内容、位置、大小等信息,以及从文件恢复界面状态的功能。代码示例展示了如何利用定时器、文件操作和序列化来实现这些功能。

功能需求

  1. 程序能够记忆位置
  2. 程序能够记忆大小
  3. 该界面中的内容能够自动保存(命名为 'd:\yyyy-mm-dd hh-mm-ss-4位随机数.txt'), 保存间隔时间自定
  4. 程序能够读取保存的内容,恢复界面状态

代码示例

using System;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace WinformAutoSave
{
    public partial class MainForm : Form
    {
        private string filePath; // 保存文件路径
        private bool isSaved; // 是否已保存
        private DateTime lastSaveTime; // 上次保存时间

        public MainForm()
        {
            InitializeComponent();

            filePath = ""; // 默认路径为空
            isSaved = true; // 默认已保存
            lastSaveTime = DateTime.Now; // 初始化上次保存时间为当前时间

            LoadFormState(); // 读取保存的界面状态
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveFormState(); // 保存界面状态
        }

        private void MainForm_LocationChanged(object sender, EventArgs e)
        {
            isSaved = false; // 位置改变后未保存
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            isSaved = false; // 大小改变后未保存
        }

        private void timerAutoSave_Tick(object sender, EventArgs e)
        {
            // 自动保存定时器触发事件
            if (!isSaved && DateTime.Now.Subtract(lastSaveTime).TotalMinutes >= 5)
            {
                // 未保存且距上次保存超过5分钟
                SaveContentToFile(); // 保存内容到文件
                isSaved = true; // 标记已保存
                lastSaveTime = DateTime.Now; // 更新上次保存时间
            }
        }

        private void SaveFormState()
        {
            // 保存界面状态到文件
            BinaryFormatter formatter = new BinaryFormatter();
            using (FileStream fs = new FileStream("formstate.dat", FileMode.Create))
            {
                FormState state = new FormState();
                state.Location = this.Location;
                state.Size = this.Size;
                formatter.Serialize(fs, state);
            }
        }

        private void LoadFormState()
        {
            // 从文件读取界面状态
            if (File.Exists("formstate.dat"))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                using (FileStream fs = new FileStream("formstate.dat", FileMode.Open))
                {
                    FormState state = (FormState)formatter.Deserialize(fs);
                    this.Location = state.Location;
                    this.Size = state.Size;
                }
            }
        }

        private void SaveContentToFile()
        {
            // 保存内容到文件
            string fileName = string.Format("d:\{0}-4位随机数.txt", DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
            using (StreamWriter sw = new StreamWriter(fileName))
            {
                sw.Write(textBoxContent.Text);
            }
            filePath = fileName; // 更新文件路径
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            // 手动保存按钮点击事件
            SaveContentToFile(); // 保存内容到文件
            isSaved = true; // 标记已保存
            lastSaveTime = DateTime.Now; // 更新上次保存时间
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            // 加载文件按钮点击事件
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件|*.txt";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (StreamReader sr = new StreamReader(openFileDialog.FileName))
                {
                    textBoxContent.Text = sr.ReadToEnd();
                }
                filePath = openFileDialog.FileName; // 更新文件路径
            }
        }

        private void buttonRestore_Click(object sender, EventArgs e)
        {
            // 恢复状态按钮点击事件
            if (File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath))
                {
                    textBoxContent.Text = sr.ReadToEnd();
                }
            }
        }
    }

    [Serializable]
    class FormState
    {
        public System.Drawing.Point Location { get; set; }
        public System.Drawing.Size Size { get; set; }
    }
}

代码解析

  1. 界面状态保存: 使用 BinaryFormatter 序列化 FormState 对象,保存到 formstate.dat 文件中,其中 FormState 类包含了窗体位置和大小信息。
  2. 界面状态恢复: 从 formstate.dat 文件中读取序列化后的 FormState 对象,并使用其属性设置窗体位置和大小。
  3. 内容保存: 定时器触发事件,将 textBoxContent 的内容写入到指定的文件。
  4. 内容恢复: 通过 OpenFileDialog 选择文件,读取文件内容到 textBoxContent。

总结

本文介绍了如何使用 C# 编写一个 Winform 程序,实现自动保存和恢复界面状态。通过利用定时器、文件操作和序列化,可以轻松实现这些功能,为用户提供更友好的使用体验。

C# Winform 程序实现自动保存和恢复界面状态

原文地址: https://www.cveoy.top/t/topic/onnZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录