记录窗体关闭位置(从窗体上次关闭的位置启动窗体)

从上次关闭位置启动窗体

基础类

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace WindowsFormsApp1
{
    public class Reg
    {
        public  static void Set(string name, object value,string item = "Software\\MySoft_ttd")
        {
            RegistryKey myReg1, myReg2;//声明注册表对象
            myReg1 = Registry.CurrentUser;//获取当前用户注册表项
            myReg2 = myReg1.CreateSubKey(item);//在注册表项中创建子项
            myReg2.SetValue(name, value);//将窗体关闭位置的x坐标写入注册表
        }
        public static object Get(string name, string item = "Software\\MySoft_ttd")
        {
            RegistryKey myReg1, myReg2;//声明注册表对象
            myReg1 = Registry.CurrentUser;//获取当前用户注册表项
            try
            {
                myReg2 = myReg1.CreateSubKey(item);//在注册表项中创建子项
                return myReg2.GetValue(name);
            }
            catch (Exception ex)
            {
                return "0";
            }
        }


    }
}

调用方法


        private void Form1_Load(object sender, EventArgs e)
        {
            //this.Location = new Point(Convert.ToInt32(Reg.Get("my_x")), Convert.ToInt32(Reg.Get("my_y")));
            //https://blog.csdn.net/u014453443/article/details/90040423
            //if (this.Location.X >= Screen.PrimaryScreen.Bounds.Width || this.Location.Y >= Screen.PrimaryScreen.Bounds.Height)
            //{
            //    this.Location = new Point(0, 0);
            //}
            this.Left = Convert.ToInt32(Reg.Get("my_x"));
            this.Top = Convert.ToInt32(Reg.Get("my_y"));
            if (this.Left >= Screen.PrimaryScreen.Bounds.Width || this.Top >= Screen.PrimaryScreen.Bounds.Height)
            {
                this.Left =0;
                this.Top = 0;   
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Reg.Set("my_x", this.Location.X.ToString());
            //Reg.Set("my_y", this.Location.Y.ToString());
            Reg.Set("my_x", this.Left.ToString());
            Reg.Set("my_y", this.Top.ToString());
        }

详细可以参考

 C#开发实例大全  基础卷

159例程

注册表内记录的信息

记录窗体关闭位置(从窗体上次关闭的位置启动窗体)_第1张图片

特此记录

anlog

2023年9月9日

你可能感兴趣的:(笔记,记录窗体关闭位置,注册表数据存储,从上次关闭位置启动窗体)