.NET WPF Remember window size between sessions

后端 未结 12 933
悲哀的现实
悲哀的现实 2020-11-30 20:33

Basically when user resizes my application\'s window I want application to be same size when application is re-opened again.

At first I though of handling SizeChange

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 20:55

    Create a string named WindowXml in your default Settings.

    Use this extension method on your Window Loaded and Closing events to restore and save Window size and location.

    using YourProject.Properties;
    using System;
    using System.Linq;
    using System.Windows;
    using System.Xml.Linq;
    
    namespace YourProject.Extensions
    {
        public static class WindowExtensions
        {
            public static void SaveSizeAndLocation(this Window w)
            {
                try
                {
                    var s = "";
                    s += GetNode("Top", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Top : w.Top);
                    s += GetNode("Left", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Left : w.Left);
                    s += GetNode("Height", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Height : w.Height);
                    s += GetNode("Width", w.WindowState == WindowState.Maximized ? w.RestoreBounds.Width : w.Width);
                    s += GetNode("WindowState", w.WindowState);
                    s += "";
    
                    Settings.Default.WindowXml = s;
                    Settings.Default.Save();
                }
                catch (Exception)
                {
                }
            }
    
            public static void RestoreSizeAndLocation(this Window w)
            {
                try
                {
                    var xd = XDocument.Parse(Settings.Default.WindowXml);
                    w.WindowState = (WindowState)Enum.Parse(typeof(WindowState), xd.Descendants("WindowState").FirstOrDefault().Value);
                    w.Top = Convert.ToDouble(xd.Descendants("Top").FirstOrDefault().Value);
                    w.Left = Convert.ToDouble(xd.Descendants("Left").FirstOrDefault().Value);
                    w.Height = Convert.ToDouble(xd.Descendants("Height").FirstOrDefault().Value);
                    w.Width = Convert.ToDouble(xd.Descendants("Width").FirstOrDefault().Value);
                }
                catch (Exception)
                {
                }
            }
    
            private static string GetNode(string name, object value)
            {
                return string.Format("<{0}>{1}", name, value);
            }
        }
    }
    

提交回复
热议问题