C#记忆窗口大小和位置的案例

发布于:2024-11-02 ⋅ 阅读:(12) ⋅ 点赞:(0)

using System;
using System.Drawing;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace StudyWinform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Load += new EventHandler(MyFormLoad);
            FormClosing += new FormClosingEventHandler(MyFormClosing);
        }

        private void MyFormLoad(object sender, EventArgs e)
        {
            // 1. 是否最大化
            if (Properties.Settings.Default.Maximized)
            {
                WindowState = FormWindowState.Maximized;
                return;
            }
            // 2. 尝试从设置中恢复窗口大小和位置
            string windowSize = Properties.Settings.Default.WindowSize;
            string windowPosition = Properties.Settings.Default.WindowPosition;
            if (!windowSize.Contains(","))
            {
                windowSize = "\"800, 450\"";
            }
            Size = JsonConvert.DeserializeObject<Size>(windowSize);
            if (!windowPosition.Contains(","))
            {
                StartPosition = FormStartPosition.WindowsDefaultBounds;
                return;
            }
            StartPosition = FormStartPosition.Manual;
            Location = JsonConvert.DeserializeObject<Point>(windowPosition);
        }

        private void MyFormClosing(object sender, FormClosingEventArgs e)
        {
            // 保存窗口大小和位置到设置中
            Properties.Settings.Default.Maximized = WindowState == FormWindowState.Maximized;
            Properties.Settings.Default.WindowSize = JsonConvert.SerializeObject(Size);
            Properties.Settings.Default.WindowPosition = JsonConvert.SerializeObject(Location);
            Properties.Settings.Default.Save();
        }
    }
}