2010-01-16 64 views
3

如何在關閉時自動保存所有屬性winforms,並在加載時自動加載所有屬性winforms? C#如何自動保存並自動加載winforms C#中的所有屬性?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
namespace SControl 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      for (int i = 0; i < Controls.Count; i++) 
      { 
       System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Controls[i])); 
       Stream stream = File.Open("test.xml", FileMode.Create); 
       x.Serialize(stream, Controls[i]); 
      } 
     } 
    } 
} 
+0

你的意思是像窗口大小,位置,模式等屬性? – 2010-01-16 05:05:49

回答

6

你的問題有點不清楚,但

如果需要保存窗體佈局的/加載看看

Windows Forms User Settings in C#

如果您需要保存/加載的對象/類看看

Load and save objects to XML using serialization

編輯:

這將告訴你如何持續表單屬性的某些設置。

Save and Restore Setings of a .NET Form using XML

也看看The Application Automation Layer - Using XML To Dynamically Generate GUI Elements--Forms And Controls

這些都將引導你,你需要去的方向。

我認爲這裏的主要目的是

  • 圖出來的時候救,什麼時候 負載,以及在哪裏存儲/檢索 這些設置。
  • 您是否正在按 用戶存儲這些設置?在數據庫中?在一個XML文件?
  • 接下來,您需要確定哪些 屬性您將是每個控件的保存/恢復的 。簡單 位置/大小設置可能不會削減它 作爲對照,將有不同的 複雜(按鈕,文本框, 的GridView,ListView控件)
  • 現在你需要弄清楚如何 迭代所有控件的形式。 控件中的按鈕,文本框,面板,控件 (面板中的控件)和 甚至可能是您的用戶控件。這個 可以使用遞歸來完成。
  • 現在您需要決定xml文件的 結構(如果您選擇 以使用xml)。這應該幾乎是 看起來像樹結構,因爲您將 查看窗體和它的 控件及其控件作爲 樹結構。
+0

我喜歡XML對象序列化,但如何保存和加載? – 2010-01-16 06:06:43

0

我不知道內置到Form基類中的任何方法自動的,而是你自己添加也不是很難。

您可以點擊窗口加載和關閉事件以將所有相關屬性緩存到後備存儲,然後稍後重新加載它們。

註冊一個事件處理程序Form.LoadForm.Closing事件處理程序。當Form.Closing發生時,將窗體狀態保存到文件或數據庫。當Form.Load發生時,請檢查是否存在保存的狀態,如果存在,請從保存的狀態重新加載。

0

您必須手動編碼要保存的屬性。

一個方便的方法是svae這些個性化設置Windows Forms Application Settings

的示例代碼段:

//save the winform position and size upon closing 
private void Form1_FormClosed(
    object sender, FormClosedEventArgs e) 
{ 
    Properties.Settings.Default.FormPosition = this.Location; 
    Properties.Settings.Default.FormSize = this.Size; 
    Properties.Settings.Default.Save(); 
} 

//load the winform position and size upon loading 
private void Form1_Load(object sender, EventArgs e) 
{ 
    this.Size = Properties.Settings.Default.FormSize; 
    this.Location = Properties.Settings.Default.FormPosition; 
} 

更多的參考資料:

+0

所有元素? Textbox1,Textbox2,Textbox3 ...? – 2010-01-16 05:24:47

+0

可以開始使用函數AutoLoad(); 可以使用函數SaveAll()退出; ? – 2010-01-16 05:26:33

+0

如果您允許用戶對錶單控件屬性(例如停靠欄,字體等)進行個性化設置,您也可以保存它們,但您必須手動對其進行編碼以保存和加載。旁觀者爲使用序列化的更自動化方法提供了很好的參考,這是另一種選擇。 'AutoLoad'和'Exit'可以用窗體事件'Form.Load'和'Form.Closing'來代替,就像Ryan Michela所說的那樣。 – 2010-01-16 05:47:23

0

將形狀轉換爲可以保存的東西的過程稱爲序列化。不幸的是,我不認爲有一種開箱即用的方式來在WinForm中序列化表單。我確實發現了How to Clone/Serialize/Copy & Paste a Windows Forms Control,並且由於表單也是控件,所以您可能可以使用代碼序列化屬性。