第一步,在配置文件添加一個鍵值對。
<!--是否自動登錄-->
<add key="autoLogin" value="true"/>
第二步,寫兩個方法,一個是讀取,一個是修改的代碼
#region 返回該軟件是否自登錄
public bool autoLogin()
{
String strAutoStar = "";
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = System.Windows.Forms.Application.ExecutablePath + ".config";
Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
var myApp = (AppSettingsSection)config.GetSection("appSettings");
strAutoStar = myApp.Settings["autoLogin"].Value;
if (strAutoStar != "true" && strAutoStar != "false")
{
autoLogin("false");
return false;
}
else
{
return bool.Parse(strAutoStar);
}
}
#endregion
#region 設置該軟件是否自登錄
public void autoLogin(String str)
{
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = System.Windows.Forms.Application.ExecutablePath + ".config";
Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
var myApp = (AppSettingsSection)config.GetSection("appSettings");
if (str != "true" && str != "false")
{
myApp.Settings["autoLogin"].Value = "false";
config.Save();
}
else
{
myApp.Settings["autoLogin"].Value = str;
config.Save();
}
}
#endregion
第三步,這設置窗體下,加一個checkbox控件
if (chkAutoLogin.Checked)
{
autoLogin("true");
}
else
{
autoLogin("false");
}
第四步,在登錄窗體中的加載事件中進行判斷
object lastValue = RegistryHelper.GetValue("UserName");//獲取上次成功登陸的用戶名
object lastPassword = RegistryHelper.GetValue("Password");//獲取上次成功登陸的密碼
if (autoLogin())
{
this.txtUserName.Text = lastValue.ToString();
txtPassword.Text = lastPassword.ToString();
tryLogin(null);
}
else
{
//正常登錄的代碼
}
補充 如何把登錄用戶名密碼寫入註冊表
。。此處省略一千字。