(1)在VS2013新建C#的windows form程序,添加引用using Microsoft.Win32;
(2)在窗体上添加ComboBox控件,添加2个button,text属性分别为“保存列表到注册表”、“结束”。
(3)添加Form1的全局变量String[] strProjectNoList=newString[5];
(4)添加注册表保存函数SaveProjectNoToRegistry()如下。具体使用RegistryKey类操作。
publicvoid SaveProjectNoToRegistry()
{
String strPNTotal =strProjectNoList.ToString();
RegistryKey hklm =Registry.LocalMachine;
RegistryKey hksoftware =hklm.OpenSubKey("software",true);
RegistryKey hkCMHICheckList =hksoftware.CreateSubKey("CMHICheckList12");
hkCMHICheckList.SetValue("ProjectNo0",strProjectNoList[0]);
hkCMHICheckList.SetValue("ProjectNo1",strProjectNoList[1]);
hkCMHICheckList.SetValue("ProjectNo2",strProjectNoList[2]);
hkCMHICheckList.SetValue("ProjectNo3",strProjectNoList[3]);
hkCMHICheckList.SetValue("ProjectNo4",strProjectNoList[4]);
hkCMHICheckList.Close();
hksoftware.Close();
hklm.Close();
}
(5)添加注册表读取函数ReadProjectNoFromRegistry()如下。读取时必须判断是否为null,第一次用时为null。
publicvoidReadProjectNoFromRegistry()
{
//从注册表读取最近5个项目,放入strProjectNoList列表。
RegistryKey hklm =Registry.LocalMachine;
RegistryKey hksoftware =hklm.OpenSubKey("software");
RegistryKey hkCMHICheckList =hksoftware.OpenSubKey("CMHICheckList12",false);
if (hkCMHICheckList !=null)
{
//如果读不到,则返回缺省值“”。
strProjectNoList[0] = (String)hkCMHICheckList.GetValue("ProjectNo0","");
strProjectNoList[1] = (String)hkCMHICheckList.GetValue("ProjectNo1","");
strProjectNoList[2] = (String)hkCMHICheckList.GetValue("ProjectNo2","");
strProjectNoList[3] = (String)hkCMHICheckList.GetValue("ProjectNo3","");
strProjectNoList[4] = (String)hkCMHICheckList.GetValue("ProjectNo4","");
hkCMHICheckList.Close();
}
hksoftware.Close();
hklm.Close();
}
(6)添加comboBox1的更新函数ComboBoxItemsRefresh()如下:
publicvoidComboBoxItemsRefresh()
{
ReadProjectNoFromRegistry();
comboBox1.Items.Clear();
comboBox1.Items.Add(strProjectNoList[0]);
comboBox1.Items.Add(strProjectNoList[1]);
comboBox1.Items.Add(strProjectNoList[2]);
comboBox1.Items.Add(strProjectNoList[3]);
comboBox1.Items.Add(strProjectNoList[4]);
comboBox1.Text =strProjectNoList[0];//选中和显示最新的那个。
}
(7)添加Form1_Load()函数初始化和加载有关内容:
privatevoid Form1_Load(object sender, EventArgs e)
{
strProjectNoList[0] ="";
strProjectNoList[1] ="";
strProjectNoList[2] ="";
strProjectNoList[3] ="";
strProjectNoList[4] ="";
ComboBoxItemsRefresh();
}
(8)添加button1、button2的处理函数:
privatevoid button2_Click(object sender, EventArgs e)
{
if (comboBox1.Text !="" &&comboBox1.Text != strProjectNoList[0] && comboBox1.Text !=strProjectNoList[1] && comboBox1.Text != strProjectNoList[2] &&comboBox1.Text != strProjectNoList[3] && comboBox1.Text !=strProjectNoList[4])
{
strProjectNoList[4] =strProjectNoList[3];
strProjectNoList[3] =strProjectNoList[2];
strProjectNoList[2] = strProjectNoList[1];
strProjectNoList[1] =strProjectNoList[0];
strProjectNoList[0] =comboBox1.Text;
SaveProjectNoToRegistry();
ComboBoxItemsRefresh();
}
}
privatevoid button1_Click(object sender, EventArgs e)
{
this.Close();
}
(9)运行后,保存和读取后界面如下: