代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
if (ReadSettings() == false)
lbContent.Items.Add("注册表中没有相关信息!");
StartPosition = FormStartPosition.Manual;
}
catch (Exception ee)
{
lbContent.Items.Add("从注册表读取信息时发生如下错误:");
lbContent.Items.Add(ee.Message);
}
}
private void btnChoose_Click(object sender, EventArgs e)
{
if (chooseColorDialog.ShowDialog() == DialogResult.OK)
BackColor = chooseColorDialog.Color;
}
void SaveSettings()
{
RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("Software", true);
RegistryKey userKey = softwareKey.CreateSubKey("myProgram");
RegistryKey selfPlacingWindowKey = userKey.CreateSubKey("SelfPlacingWindow");
selfPlacingWindowKey.SetValue("BackColor",(object)BackColor.ToKnownColor());
selfPlacingWindowKey.SetValue("Red", (object)(int)BackColor.R);
selfPlacingWindowKey.SetValue("Green", (object)(int)BackColor.G);
selfPlacingWindowKey.SetValue("Blue", (object)(int)BackColor.B);
selfPlacingWindowKey.SetValue("Width", (object)Width);
selfPlacingWindowKey.SetValue("Height", (object)Height);
selfPlacingWindowKey.SetValue("X", (object)DesktopLocation.X);
selfPlacingWindowKey.SetValue("Y", (object)DesktopLocation.Y);
selfPlacingWindowKey.SetValue("WindowState",(object)WindowState.ToString());
}
bool ReadSettings()
{
RegistryKey softwareKey = Registry.LocalMachine.OpenSubKey("Software");
RegistryKey userKey = softwareKey.OpenSubKey("myProgram");
if (userKey == null)
return false;
RegistryKey selfPlacingWindowKey = userKey.OpenSubKey("SelfPlacingWindow");
if (selfPlacingWindowKey == null)
return false;
else
lbContent.Items.Add("Successfully opened key " + selfPlacingWindowKey.ToString());
//以下从注册表读取数据
lbContent.Items.Add("注册表信息如下:");
int redComponent = (int)selfPlacingWindowKey.GetValue("Red");
int greenComponent = (int)selfPlacingWindowKey.GetValue("Green");
int blueComponent = (int)selfPlacingWindowKey.GetValue("Blue");
this.BackColor = Color.FromArgb(redComponent, greenComponent,blueComponent);
lbContent.Items.Add("Background color: " + BackColor.Name);
int X = (int)selfPlacingWindowKey.GetValue("X");
int Y = (int)selfPlacingWindowKey.GetValue("Y");
this.DesktopLocation = new Point(X, Y);
lbContent.Items.Add("Desktop location: " +DesktopLocation.ToString());
this.Height = (int)selfPlacingWindowKey.GetValue("Height");
this.Width = (int)selfPlacingWindowKey.GetValue("Width");
lbContent.Items.Add("Size: " + new Size(Width, Height).ToString());
string initialWindowState = (string)selfPlacingWindowKey.GetValue("WindowState");
lbContent.Items.Add("Window State: " + initialWindowState);
this.WindowState = (FormWindowState)FormWindowState.Parse(WindowState.GetType(), initialWindowState);
return true;
}
}
}