WinForm自动记录从上次关闭位置启动窗体

次功能主要是通过在注册表中读写窗体的Location属性来实现的。在窗体关闭前处理窗体的FormClosed事件,将窗体的Location属性值写入注册表,然后在窗体的Load事件中从注册表中读取保存的数据。
 

(1)Location属性
Point结果,表示窗体的左上角相对桌面的 左上角的坐标。
(2)读写注册表
c#中对注册表进行读写,主要是通过RegistryKey类的GetValue和SetValue方法来实现的。
代码
/// <summary>
/// 窗体加载时获取窗体上次结束时的位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
RegistryKey myReg1, myReg2; //声明注册表对象
myReg1 = Registry.CurrentUser; //获取当前用户注册表项
try
{
myReg2 = myReg1.CreateSubKey("Software\\MySoft"); //在注册表项中创建子项
this.Location = new Point(Convert.ToInt16(myReg2.GetValue("1")), Convert.ToInt16(myReg2.GetValue("2"))); //设置窗体的显示位置
}
catch
{

}
}
/// <summary>
/// 窗体关闭前记录窗体的当前位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
RegistryKey myReg1, myReg2; //声明注册表对象
myReg1 = Registry.CurrentUser; //获取当前用户注册表项
myReg2 = myReg1.CreateSubKey("Software\\MySoft"); //在注册表项中创建子项 
try
{
myReg2.SetValue("1", this.Location.X.ToString());
myReg2.SetValue("2", this.Location.Y.ToString());
}
catch
{

}
}

 

posted @ 2019-07-29 18:34  跟着阿笨一起玩.NET  阅读(784)  评论(0编辑  收藏  举报