目录
1.操作方法
(1)Location属性
(2)读写注册表
(3)SetValue方法
(4)命名空间
2.示例
实际开发中,有很多软件都有一个通用的功能,即从上次关闭位置启动窗体,使用C#语言可以通过在注册表中读写窗体的Location属性来实现从上次关闭位置启动窗体的功能。
1.操作方法
在窗体关闭前处理窗体的FormClosed事件,将窗体的Location属性值写入注册表,然后在窗体的Load事件中从注册表中读取保存的数据,设置窗体的Location属性值,从而实现了从上次关闭位置启动窗体的功能。
(1)Location属性
该属性用来获取或设置窗体的左上角相对于桌面的左上角坐标。语法格式如下:
[SettingsBindableAttribute(true)]
public Point Location{get;set;}
参数说明
属性值:Point结构,表示窗体的左上角相对于桌面的左上角坐标。
(2)读写注册表
C#中对注册表进行读写,主要是通过RegistryKey类的GetValue方法和SetValue方法来实现的,其中,GetValue方法用来检索与指定名称关联的值,其最常用的语法格式如下:
public Object GetValue(string name)
参数说明
name:要检索的值的名称。
返回值:与name关联的值;如果未找到name,则为null。
(3)SetValue方法
SetValue方法用来设置注册表项中的名称/值对的值,其最常用的语法格式如下:
public void SetValue(string name,Object value)
参数说明
name:要存储的值的名称。
value:要存储的数据。
(4)命名空间
使用RegistryKey类时,首先需要在命名空间区域添加Microsoft.Win32命名空间。
2.示例
// 从上次窗体关闭的位置打开窗体
// Form1.cs
using Microsoft.Win32;namespace _159
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){RegistryKey myReg1, myReg2; //声明注册表对象myReg1 = Registry.CurrentUser; //获取当前用户注册表项try{myReg2 = myReg1.CreateSubKey("Software\\MySoft");//在注册表项中创建子项Location = new Point(Convert.ToInt16(myReg2.GetValue("1")), Convert.ToInt16(myReg2.GetValue("2")));//设置窗体的显示位置}catch { }}private void Form1_FormClosed(object sender, FormClosedEventArgs e){RegistryKey myReg1, myReg2; //声明注册表对象myReg1 = Registry.CurrentUser; //获取当前用户注册表项myReg2 = myReg1.CreateSubKey("Software\\MySoft");//在注册表项中创建子项try{myReg2.SetValue("1", Location.X.ToString()); //将窗体关闭时x坐标写入注册表myReg2.SetValue("2", Location.Y.ToString()); //将窗体关闭时y坐标写入注册表}catch { }}}
}
// Form1.Designer.cs
namespace _159
{partial class Form1{/// <summary>/// Required designer variable./// </summary>private System.ComponentModel.IContainer components = null;/// <summary>/// Clean up any resources being used./// </summary>/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>protected override void Dispose(bool disposing){if (disposing && (components != null)){components.Dispose();}base.Dispose(disposing);}#region Windows Form Designer generated code/// <summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>private void InitializeComponent(){SuspendLayout();// // Form1// AutoScaleDimensions = new SizeF(7F, 17F);AutoScaleMode = AutoScaleMode.Font;ClientSize = new Size(324, 191);Name = "Form1";Text = "从上次关闭位置启动窗体";FormClosed += Form1_FormClosed;Load += Form1_Load;ResumeLayout(false);}#endregion}
}