先來看個效果:

最近在做一外貿進口軟件,使用C/S架構開發。為了用戶使用方便,這不嘗試增加記住用戶名密碼的功能,並且可以設置開機自動啟動軟件,一切都是為了減少用戶的點擊操作。
可以有多種方式來保存用戶信息,比如存成本地文件、xml、注冊表、更有甚者存入數據庫。個人認為存到數據庫裡這個操作在沒登陸前就發生有些不太好,先去數據庫取密碼回來放到輸入框裡等著點擊感覺不太好。
最後采用了注冊表的方式來保存這些信息。這裡為了演示沒有對保存進注冊表的密碼進行加密,為了安全應該繼續對保存的密碼加密。
private void ckbKeepInfo_CheckStateChanged(object sender, EventArgs e)
{
RegistryKey location = Registry.LocalMachine;
RegistryKey soft = location.OpenSubKey("SOFTWARE", true);//可寫
RegistryKey myPass = soft.CreateSubKey("FTLiang");
myPass.SetValue("s1", tbUserName.Text);
myPass.SetValue("s2", tbPassword.Text);
myPass.SetValue("s3", ckbKeepInfo.Checked);
}
自動登陸:
private void ckbAutoStart_CheckStateChanged(object sender, EventArgs e)
{
if(ifFistIn == false)
{
RegistryKey location = Registry.LocalMachine;
RegistryKey soft = location.OpenSubKey("SOFTWARE", true);//可寫
RegistryKey myPass = soft.CreateSubKey("FTLiang");
myPass.SetValue("s4", ckbAutoStart.Checked);
if (ckbAutoStart.Checked)
{
string exeDir = Application.ExecutablePath;//要啟動的程序絕對路徑
RegistryKey rk = Registry.LocalMachine;
RegistryKey softWare = rk.OpenSubKey("SOFTWARE");
RegistryKey microsoft = softWare.OpenSubKey("Microsoft");
RegistryKey windows = microsoft.OpenSubKey("Windows");
RegistryKey current = windows.OpenSubKey("CurrentVersion");
RegistryKey run = current.OpenSubKey(@"Run", true);//這裡必須加true就是得到寫入權限
run.SetValue("FTStart", exeDir);
}
else
{
string exeDir = Application.ExecutablePath;//要啟動的程序絕對路徑
RegistryKey rk = Registry.LocalMachine;
RegistryKey softWare = rk.OpenSubKey("SOFTWARE");
RegistryKey microsoft = softWare.OpenSubKey("Microsoft");
RegistryKey windows = microsoft.OpenSubKey("Windows");
RegistryKey current = windows.OpenSubKey("CurrentVersion");
RegistryKey run = current.OpenSubKey(@"Run", true);//這裡必須加true就是得到寫入權限
run.DeleteValue("FTStart");//這裡必須加true就是得到寫入權限
}
}
}
初始窗體顯示:
private void FmLogin_Load(object sender, EventArgs e)
{
//從注冊表中讀取 是否保存了用戶名密碼 自動啟動配置
try
{
RegistryKey location = Registry.LocalMachine;
RegistryKey soft = location.OpenSubKey("SOFTWARE", false);//可寫
RegistryKey myPass = soft.OpenSubKey("FTLiang", false);
tbUserName.Text = myPass.GetValue("s1").ToString();
string s2 = myPass.GetValue("s2").ToString();
bool ifSave = Convert.ToBoolean(myPass.GetValue("s3"));
ckbKeepInfo.Checked = ifSave;
bool ifSave2 = Convert.ToBoolean(myPass.GetValue("s4"));
ckbAutoStart.Checked = ifSave2;
if (ifSave)
{
tbPassword.Text = s2;
}
else
{
tbPassword.Text = "";
}
ifFistIn = false; //程序已啟動完畢,可以執行注冊表相關動作
}
catch (Exception ex) {
//todo something
}
}