首页 > 代码库 > 使用注册表实现保存窗体默认设置

使用注册表实现保存窗体默认设置

ColorDialog ChooseColorDialog=new ColorDialog();


public Form1()
{
InitializeComponent();
buttonChooseColor.Click+=new EventHandler(OnClickChooseColor);
try
{
if (ReadSettings() == false)
listBoxMessages.Items.Add("No information in registry");
else
listBoxMessages.Items.Add("Information read in form registry");
StartPosition = FormStartPosition.Manual;
}
catch (Exception ex)
{
listBoxMessages.Items.Add("A problem occurred reading in data from registry:");
listBoxMessages.Items.Add(ex.Message);
}
}

private void OnClickChooseColor(object Sender, EventArgs e)
{
if (ChooseColorDialog.ShowDialog() == DialogResult.OK)
BackColor = ChooseColorDialog.Color;
}

private void SaveSttings()
{
RegistryKey SoftwareKey = Registry.LocalMachine.OpenSubKey("Software", true);
RegistryKey WroxKey = SoftwareKey.CreateSubKey("WroxPress");
RegistryKey SelfPlacingWindowsKey = WroxKey.CreateSubKey("SelfPlacingWindow");
SelfPlacingWindowsKey.SetValue("BackColor",(object)BackColor.ToKnownColor());
SelfPlacingWindowsKey.SetValue("Red",(object)(int)BackColor.R);
SelfPlacingWindowsKey.SetValue("Green", (object)(int)BackColor.G);
SelfPlacingWindowsKey.SetValue("Blue", (object)(int)BackColor.B);
SelfPlacingWindowsKey.SetValue("Width", (object)Width);
SelfPlacingWindowsKey.SetValue("Height", (object)Height);
SelfPlacingWindowsKey.SetValue("X", (object)DesktopLocation.X);
SelfPlacingWindowsKey.SetValue("Y", (object)DesktopLocation.Y);
SelfPlacingWindowsKey.SetValue("WindowState", (object)WindowState.ToString());
}

private bool ReadSettings()
{
RegistryKey SoftWareKey = Registry.LocalMachine.OpenSubKey("Software");
RegistryKey WroxKey = SoftWareKey.OpenSubKey("WroxPress");
if (WroxKey == null)
return false;
RegistryKey SelfPlacingWindowKey = WroxKey.OpenSubKey("SelfPlacingWindow");
if (SelfPlacingWindowKey == null)
return false;
else
listBoxMessages.Items.Add("Successfully opened key" + SelfPlacingWindowKey.ToString());
int RedComponent = (int) SelfPlacingWindowKey.GetValue("Red");
int GreenComponent = (int) SelfPlacingWindowKey.GetValue("Green");
int BlueComponent = (int) SelfPlacingWindowKey.GetValue("Blue");
BackColor = Color.FromArgb(RedComponent, GreenComponent, BlueComponent);
listBoxMessages.Items.Add("Backgroud color:" + BackColor.Name);
int X = (int) SelfPlacingWindowKey.GetValue("X");
int Y = (int) SelfPlacingWindowKey.GetValue("Y");
DesktopLocation=new Point(X,Y);
listBoxMessages.Items.Add("Desktop location:" + DesktopLocation.ToString());
Height = (int) SelfPlacingWindowKey.GetValue("Height");
Width = (int) SelfPlacingWindowKey.GetValue("Width");
listBoxMessages.Items.Add("Size:" + new Size(Width, Height).ToString());
string InitialWindowState = (string) SelfPlacingWindowKey.GetValue("WindowState");
listBoxMessages.Items.Add("Window State:" + InitialWindowState);
WindowState = (FormWindowState) FormWindowState.Parse(WindowState.GetType(), InitialWindowState);
return true;

}

使用注册表实现保存窗体默认设置