从上次启动的位置启动窗体

实现效果:

  

知识运用:

   实现原理:通过在注册表中读写窗体的Location属性来实现的

   在窗体的FormClosed事件中将Location属性值写入注册表 在Load事件中从注册表中读取值并进行设置

   Location属性:获取或设置窗体的左上角相对于桌面的左上角坐标

  public Point Location { get;set }   属性值为Point结构,表是窗体左上角相对于桌面的左上角坐标

  读写注册表:RegistryKey类的GetValue方法和SetValue方法来实现    //添加Microsoft.Win32命名空间

  public Object GetValue( string name )    //name:要索引的值的名称  //返回值:与name关联的值      //找不到则返回null

实现代码:

        private void Form1_Load(object sender, EventArgs e)
        {
            RegistryKey reg1, reg2;    //声明注册表对象
            reg1 = Registry.CurrentUser;       //获取当前用户注册表
            try
            {
                reg2 = reg1.CreateSubKey("Software\MySoft");   //在注册表中创建子项
                this.Location = new Point(Convert.ToInt16(reg2.GetValue("1")),Convert.ToInt16(reg2.GetValue("2")));
            }
            catch { }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            RegistryKey reg1, reg2;
            reg1 = Registry.CurrentUser;
            reg2 = reg1.CreateSubKey("Software\MySoft");
            try
            {
                reg2.SetValue("1",this.Location.X.ToString());
                reg2.SetValue("2",this.Location.Y.ToString());
            }
            catch { }
        }
原文地址:https://www.cnblogs.com/feiyucha/p/10092113.html