winform项目中,经常需要记住用户名和密码,可以将用户名和密码写入注册表或者文件的形式实现.
这里展示一下写入注册表的功能,
1.写入注册表
private void zbtnsave_Click(object sender, EventArgs e)
{
try
{
string strPath = "HKEY_CURRENT_CONFIG\\UFWin";//设默认值
object username = (object)this.zusername.Text.Trim();
object userpwd = (object)this.zpwd.Text.Trim();
Registry.SetValue(strPath, "用户名", username, RegistryValueKind.String);
Registry.SetValue(strPath, "密码", userpwd, RegistryValueKind.String);
MessageBox.Show("成功写入注删表");
}
catch { return; }
}
2.从注册表中读取
public void load()
{
try
{
RegistryKey rk = Registry.CurrentConfig.OpenSubKey("UFWin");
if (rk == null) { return; }
if (rk.GetValue("用户名", "Null") != null)
{
zusername.Text = rk.GetValue("用户名", "Null").ToString();
}
if (rk.GetValue("用户名", "Null") != null)
{
zpwd.Text = rk.GetValue("密码", "Null").ToString();
}
}
catch { return; }
}
实现效果: