問題描述:在winform中想實現像BS中類似Session的功能,放上需要的信息,在程序中都可以訪問到。
解決方案:由於自己很長時間沒有做過winform的程序,一時間竟然手足無措起來。后來發現winform實現起來也十分簡單。
一、在窗體Form1中創建static 用戶類
1 /// <summary> 2 /// 當前登錄用戶信息 3 /// </summary> 4 public static class CurrentUser 5 { 6 /// <summary> 7 /// 用戶名 8 /// </summary> 9 public static string userName { get; set; } 10 11 12 /// <summary> 13 /// 登錄時間 14 /// </summary> 15 public static DateTime LoginTime { get; set; } 16 17 }
在page_load中為它賦值
1 private void Form1_Load(object sender, EventArgs e) 2 { 3 CurrentUser.userName = "test"; 4 CurrentUser.LoginTime = DateTime.Now; 5 }
在點擊事件中打開新窗體
1 private void button1_Click(object sender, EventArgs e) 2 { 3 int x = this.Location.X; 4 int y = this.Location.Y; 5 this.Hide(); 6 Form2 secondForm = new Form2(); 7 secondForm.Location = new Point(x, y); 8 secondForm.Show(); 9 }
效果如圖:

二、在form2窗體中直接訪問靜態類的數值即可
1 private void Form2_Load(object sender, EventArgs e) 2 { 3 this.txtUserName.Text = Form1.CurrentUser.userName; 4 this.txtLoginTime.Text = Form1.CurrentUser.LoginTime.ToString("yyyy-MM-dd HH:mm:ss"); 5 }
效果:

寫在后面的話:其實現在想想,winform並不需要session,因為我的理解中session是保存用戶和服務器之間的會話信息,尤其是多用戶訪問網站時,尤顯得重要。但是winform程序類似於單機軟件,相當於一個用戶對winform程序,也不知道這樣理解對不對。對於winform的開發理解得太淺了,有時候會經常把web開發的思路帶到winform中,發現其實兩者還是有很大差別的。繼續要努力學習呢~
