Recently C# Corner published an excellent article called "Saving and Restoring the Location, Size and Windows State of a .NET Form" by Joel Matthias. In this article Mr. Matthias shows how a form can remember its location and size by writing the values to the registry when the form closes and by reading them from the registry when the form loads. Even though there are advantages to writing to the registry, there are times when a programmer does not want to impact anything outside of the directory where the program resides. This article explains how to save and restore settings by reading from and writing to an XML file instead of to the registry.The XML file has a column for each of the settings that the form needs remember. (The schema for the XML is included in the downloadable code.)<?xml version="1.0" encoding="utf-8" ?><?xml version="1.0" standalone="yes"?><Settings><root><Left>104</Left><Top>108</Top><Width>277</Width><Height>254</Height><WindowState>0</WindowState><bgColor>LightGray</bgColor></root></Settings>When the form loads, it reads the XML file into a dataset. The location, size, WindowState, and BackColor of the form are set to the values from the XML file.private void frmSaveSettings_Load(object sender, System.EventArgs e){ds = new DataSet();ds.ReadXml(m_xmlPath);DataRow dr = ds.Tables[0].Rows[0];Left = (int)dr["Left"];Top = (int)dr["Top"];m_Width = (int)dr["Width"];m_Height = (int)dr["Height"];m_WindowState = (FormWindowState)dr["WindowState"];m_bgColor = dr["bgColor"].ToString();this.Location = new Point(m_Left, m_Top);this.Size = new Size(m_Width, m_Height);this.WindowState = m_WindowState;this.BackColor = Color.FromName(m_bgColor);}There are three events where the form settings are reset. The Resize event fires when the size of the form is changed and resets the width and height. The Move event fires when the form is moved and resets the left, top, and WindowState. The SelectedIndexChanged event fires when the user chooses color name from the combobox and resets the BackColor of the form and BackColor value.private void frmSaveSettings_Resize(object sender, System.EventArgs e){// set sizem_Width = this.Width;m_Height = this.Height;}private void frmSaveSettings_Move(object sender, System.EventArgs e){// set location and windowstatem_Left = this.Left;m_Top = this.Top;m_WindowState = this.WindowState;}private void cbColors_SelectedIndexChanged(object sender, System.EventArgs e){this.BackColor = Color.FromName(cbColors.SelectedItem.ToString());m_bgColor = this.BackColor.Name;}Finally, when the form closes, the dataset items are set to the form settings.
private
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: