注册表是Microsoft Windows中的一个重要的数据库,用于存储系统和应用程序的设置信息,有时候程序需要对注册表进行读写的工作,这里介绍下如何在C#里面操作注册表。
//需要先引用Microsoft.Win32
using Microsoft.Win32;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
//写注册表 public void WriteRegistry() { RegistryKey SoftwareKey=Registry.LocalMachine.OpenSubKey("Software",true); RegistryKey MovecontKey=SoftwareKey.CreateSubKey("Movecont");//建立 RegistryKey SelfPlaceKey=MovecontKey.CreateSubKey("SelfPlace");//建立 SelfPlaceKey.SetValue("BackColor",(object)BackColor.ToKnownColor());//写 SelfPlaceKey.SetValue("Red",(object)(int)BackColor.R);//红 SelfPlaceKey.SetValue("Green",(object)(int)BackColor.G);//绿 SelfPlaceKey.SetValue("Blue",(object)(int)BackColor.B);//蓝 SelfPlaceKey.SetValue("Width",(object)Width);//宽 SelfPlaceKey.SetValue("Height",(object)Height);//高 SelfPlaceKey.SetValue("X",(object)DesktopLocation.X);//左上角X坐标 SelfPlaceKey.SetValue("Y",(object)DesktopLocation.Y);//左上角Y坐标 SelfPlaceKey.SetValue("WindowState",(object)WindowState.ToString());//左上角Y坐标 } //读注册表 public bool ReadRegistry() { RegistryKey SoftwareKey=Registry.LocalMachine.OpenSubKey("Software",true); RegistryKey MovecontKey=SoftwareKey.OpenSubKey("Movecont");//建立 if(MovecontKey==null) return false; RegistryKey SelfPlaceKey=MovecontKey.OpenSubKey("SelfPlace");//建立 if(SelfPlaceKey==null) return false; else this.listBoxMessages.Items.Add("成功打开注册表!"); int Red=(int)SelfPlaceKey.GetValue("Red"); int Green=(int)SelfPlaceKey.GetValue("Green"); int Blue=(int)SelfPlaceKey.GetValue("Blue"); BackColor=Color.FromArgb(Red,Green,Blue); this.listBoxMessages.Items.Add("Backcolor Name:"+BackColor.Name); int X=(int)SelfPlaceKey.GetValue("X"); int Y=(int)SelfPlaceKey.GetValue("Y"); DesktopLocation=new Point(X,Y); this.listBoxMessages.Items.Add("Location:"+DesktopLocation.ToString()); Width=(int)SelfPlaceKey.GetValue("Width"); Height=(int)SelfPlaceKey.GetValue("Height"); this.listBoxMessages.Items.Add("Size:"+new Size(Width,Height).ToString()); string Initstate=(string)SelfPlaceKey.GetValue("WindowState"); //****枚举类型数据的Parse WindowState=(FormWindowState)FormWindowState.Parse(WindowState.GetType(),Initstate); return true; } |