c save window location size action class (serialization and file read write)

  • 2020-05-26 09:57:08
  • OfStack

Record the location and size of the last closed window


namespace PDSafe.Base
{
    public class Setting
    {
        ///<summary>
        ///  Serialize the object into an array of bytes 
        ///</summary>
        public static byte[] SerializeObject(object obj)
        {
            if (obj == null)
                return null;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Close();
            return bytes;
        }
        ///<summary>
        ///  Deserialize a byte array into an object 
        ///</summary>
        public static object DeserializeObject(byte[] bytes)
        {
            object obj = null;
            if (bytes == null)
                return obj;
            MemoryStream ms = new MemoryStream(bytes);
            ms.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                obj = formatter.Deserialize(ms);
            }
            catch { obj = null; }
            ms.Close();
            return obj;
        }
        public static bool Save(string path, object value, bool isCeranew)
        {
            // If the create file does not exist 
            FileStream fs;
            if ((!File.Exists(path)) && isCeranew)
            {
                try
                {
                    fs = File.Create(path);
                }
                catch
                {
                    return false;
                }
            }
            // Open if it exists 
            else
            {
                try
                {
                    fs = File.Open(path, FileMode.Open, FileAccess.Write);
                }
                catch
                {
                    return false;
                }
            }
            // Write files 
            byte[] buffer = SerializeObject(value);
            try
            {
                for (long i = 0; i < buffer.LongLength; i++)
                    fs.WriteByte(buffer[i]);
            }
            catch
            {
                return false;
            }
            fs.Close();
            return true;
        }
        public static object Read(string path)
        {
            FileStream fs;
            try
            {
                fs = File.OpenRead(path);
            }
            catch
            {
                return null;
            }
            // Read in the cache 
            StreamReader sreader = new StreamReader(fs);
            string str = sreader.ReadToEnd();
            fs.Close();
            sreader.Close();
            // Analysis of the content 
            byte[] buffer = Encoding.Default.GetBytes(str);
            return DeserializeObject(buffer);
        }
        [Serializable]
        public struct FormSizeandLocation
        {
            public int SizeW;
            public int SizeH;
            public int LocationX;
            public int LocationY;
            public int Style;
        }
      private static  Setting.FormSizeandLocation fsp = new Setting.FormSizeandLocation();
        public static void AddRenewFormSizeControl(Form form)
        {
            form.FormClosing += new FormClosingEventHandler(FormcloseEvent);
            form.Load += new EventHandler(FormloadEvent);
         }
        private static void FormcloseEvent(object sender, EventArgs e)
        {
            Form form = (Form)sender;
            switch (form.WindowState)
            {
                case FormWindowState.Maximized:
                    fsp.Style = 2;
                    fsp.SizeW = form.Width;
                    fsp.SizeH = form.Height;
                    fsp.LocationX = form.Location.X;
                    fsp.LocationY = form.Location.Y;
                    break;
                case FormWindowState.Minimized:
                    fsp.Style = 1;
                    break;
                case FormWindowState.Normal:
                    fsp.Style = 0;
                    fsp.SizeW = form.Width;
                    fsp.SizeH = form.Height;
                    fsp.LocationX = form.Location.X;
                    fsp.LocationY = form.Location.Y;
                    break;
            }
            Setting.Save(Directory.GetCurrentDirectory() + @"\" + "Location.set", fsp, true);
        }
        private static void FormloadEvent(object sender, EventArgs e)
        {
            Form form = (Form)sender;
            object result = Setting.Read(Directory.GetCurrentDirectory() + @"\" + "Location.set");
            if (result != null)
            {
                fsp = (Setting.FormSizeandLocation)result;
                switch (fsp.Style)
                {
                    case 2:
                        form.WindowState = FormWindowState.Maximized;
                        break;
                    default:
                        form.WindowState = FormWindowState.Normal;
                        break;
                }
                form.Left = fsp.LocationX;
                form.Top = fsp.LocationY;
                form.Size = new Size(fsp.SizeW, fsp.SizeH);

            }
        }
    }
}

The basic function is to save data of a structure type
bool Save (filePath,value,true);
And then there's the file that reads the data that's being saved, and it reads from it, and the structure is boxed, and all you have to do is unbox it
object result = Save (filePath, data instance to be saved, true)
if (result! = null) // confirm that the file exists and was read successfully

Combining these two functions, can you record the position and size of the window? Of course, the first thing to do is to declare a structure to save the size and position as well as the state


 [Serializable]
        public struct FormSizeandLocation
        {
            public int SizeW;
            public int SizeH;
            public int LocationX;
            public int LocationY;
            public int Style;
        }

And then I'm going to save and set it up, and I'm going to do it in line 108-172, How does it work, okay?
Ask the user to give an instance of a window
Subscribe to the Load and Closing events of the instance
Read the saved file in the load event and change the location and size of the instance
Save the size and location in the closing event
AddRenewFormSizeControl (this);
// you only need 1 line of code, 1 must be written after the InitializeComponent function. You can't write it in load

Note that the saved file is the working path + Location.set you can also rewrite this yourself.


Related articles: