開發 Windows Forms 程式,想要在關閉程式時儲存控制項狀態,該如何撰寫?
2011/12/21 有篇文章很不錯 在.net中读写config文件的各种方法
範例下載
問題的來龍去脈
開發 Windows Forms 程式,想要在關閉程式時儲存控制項狀態,例如紀錄 TextBox 上的帳號與密碼資訊,該如何撰寫?
問題的發生原因
想要儲存使用者輸入的資料方法有很多,例如透過 *.xml 與 *.config。在此我們透過應用程式設定來儲存設定資料,當關閉 Windows Forms 程式時將 TextBox 資料做儲存,當程式開啟時,將儲存的資料讀取出來。
想要了解更多資訊,請參考 MSDN Windows Form 的應用程式設定 提供的說明。
問題的解決方法
1. 開啟方案,在您的 Windows Forms 專案上按滑鼠右鍵,選擇 [屬性]。
2. 選擇 [設定] 頁籤,會看到應用程式設定相關資訊,由於我們要儲存帳號與密碼兩個 TextBox 的資料,因此建立兩個 Setting,分別是 UsernameSetting 與 PasswordSetting,型別是字串 string,範圍選擇 User 可做讀取跟儲存,假如範圍設定成 Application 的話則只能讀取不能儲存。
3. 加入表單 Load 事件與 FormClosing 事件,然後在 FormClosing 事件撰寫儲存設定程式碼,在 Load 事件撰寫讀取設定程式碼。
C#
private void DemoForm_Load(object sender, EventArgs e)
{
// 在 Load 事件撰寫讀取設定程式碼
// 讀取設定到帳號 TextBox.Text
this.txtUserName.Text = wfAppDemo.Properties.Settings.Default.UsernameSetting;
// 讀取設定到密碼 TextBox.Text
this.txtPassword.Text = wfAppDemo.Properties.Settings.Default.PasswordSetting;
}
private void DemoForm_FormClosing(object sender, FormClosingEventArgs e)
{
// 在 FormClosing 事件撰寫儲存設定程式碼
// 將帳號 TextBox.Text 儲存到 UsernameSetting
wfAppDemo.Properties.Settings.Default.UsernameSetting = this.txtUserName.Text;
// 將密碼 TextBox.Text 儲存到 PasswordSetting
wfAppDemo.Properties.Settings.Default.PasswordSetting = this.txtPassword.Text;
wfAppDemo.Properties.Settings.Default.Save();
}
VB
Private Sub DemoForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' 在 Load 事件撰寫讀取設定程式碼
' 讀取設定到帳號 TextBox.Text
Me.txtUserName.Text = My.Settings.UsernameSetting
' 讀取設定到密碼 TextBox.Text
Me.txtPassword.Text = My.Settings.PasswordSetting
End Sub
Private Sub DemoForm_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
' 在 FormClosing 事件撰寫儲存設定程式碼
' 將帳號 TextBox.Text 儲存到 UsernameSetting
My.Settings.UsernameSetting = Me.txtUserName.Text
' 將密碼 TextBox.Text 儲存到 PasswordSetting
My.Settings.PasswordSetting = Me.txtPassword.Text
End Sub
其他相關資訊