andrew4582

WindowPositionData WPF

Jul 3rd, 2014
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.26 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Windows;
  4. using System.Xml.Serialization;
  5.  
  6. namespace System.Windows
  7. {
  8.     /*
  9.     public MainWindow()
  10.     {
  11.         InitializeComponent();
  12.         WindowPositionData.LoadWindowPosision(this);
  13.         this.Closing += (s, e) => WindowPositionData.SaveWindowPosision(this);
  14.     }
  15.      */
  16.  
  17.     /// <summary>
  18.     /// Class used to persist window's position
  19.     /// </summary>
  20.     [XmlRoot("WindowPositionData")]
  21.     [Serializable]
  22.     public class WindowPositionData
  23.     {
  24.         /// <summary>
  25.         /// True to ignore setting window position on startup, changed in user options
  26.         /// </summary>
  27.         public bool IgnoreOnStartup { get; set; }
  28.  
  29.         /// <summary>
  30.         /// True to ignore the main dock layout on startup, changed in user options
  31.         /// </summary>
  32.         public bool IgnoreDockLayoutOnStartup { get; set; }
  33.  
  34.         public double WindowTop { get; set; }
  35.  
  36.         public double WindowLeft { get; set; }
  37.  
  38.         public double WindowHeight { get; set; }
  39.  
  40.         public double WindowWidth { get; set; }
  41.  
  42.         public System.Windows.WindowState WindowState { get; set; }
  43.  
  44.         public bool AllValuesZero()
  45.         {
  46.             return WindowTop <= 0 && WindowLeft <= 0 && WindowHeight <= 0 && WindowWidth <= 0;
  47.         }
  48.  
  49.         #region static methods
  50.  
  51.         public static WindowPositionData MainWindowPosition { get; private set; }
  52.  
  53.         public static void LoadWindowPosision(Window win, string fileName = null)
  54.         {
  55.             WindowPositionData data = GetDataFromFile(win, fileName);
  56.             MainWindowPosition = data;
  57.             if (!data.IgnoreOnStartup)
  58.             {
  59.                 SetWindowPosition(win, data);
  60.             }
  61.         }
  62.  
  63.         public static void SaveWindowPosition(Window win, string fileName = null)
  64.         {
  65.             WindowPositionData data = MainWindowPosition ?? new WindowPositionData();
  66.             GetWindowPosition(win, data);
  67.             if (MainWindowPosition != null)
  68.             {
  69.                 data.IgnoreOnStartup = MainWindowPosition.IgnoreOnStartup;
  70.             }
  71.             SaveDataToFile(win, data, fileName);
  72.         }
  73.  
  74.         public static void GetWindowPosition(Window win, WindowPositionData data)
  75.         {
  76.             data.WindowWidth = win.Width;
  77.             data.WindowHeight = win.Height;
  78.             data.WindowTop = win.Top;
  79.             data.WindowLeft = win.Left;
  80.             data.WindowState = win.WindowState;
  81.         }
  82.  
  83.         public static void SetWindowPosition(Window win, WindowPositionData data)
  84.         {
  85.             if (data.AllValuesZero())
  86.             {
  87.                 win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
  88.             }
  89.             else
  90.             {
  91.                 win.WindowStartupLocation = WindowStartupLocation.Manual;
  92.             }
  93.  
  94.             if (data.WindowWidth > 0)
  95.                 win.Width = data.WindowWidth;
  96.             if (data.WindowHeight > 0)
  97.                 win.Height = data.WindowHeight;
  98.             if (data.WindowTop > 0)
  99.                 win.Top = data.WindowTop;
  100.             else
  101.             {
  102.                 if (double.IsNaN(win.Top))
  103.                     win.Top = 0;
  104.             }
  105.             win.Left = data.WindowLeft;
  106.  
  107.             //if (data.WindowLeft > 0)
  108.                
  109.             //else
  110.             //{
  111.             //  if (double.IsNaN(win.Left))
  112.             //      win.Left = 0;
  113.             //}
  114.  
  115.             SizeToFit(win);
  116.             EnsureWindowIsInBounds(win);
  117.  
  118.             if (data.WindowState != WindowState.Minimized)
  119.             {
  120.                 win.WindowState = data.WindowState;
  121.             }
  122.         }
  123.  
  124.         static WindowPositionData GetDataFromFile(Window win, string filePath = null)
  125.         {
  126.             string datafilePath = GetDataFilePath(win, filePath);
  127.             try
  128.             {
  129.                 if (File.Exists(datafilePath))
  130.                 {
  131.                     return WindowPositionData.DeserializeFromXml(File.ReadAllText(datafilePath));
  132.                 }
  133.                 else
  134.                     return new WindowPositionData();
  135.             }
  136.             catch
  137.             {
  138.                 return new WindowPositionData();
  139.             }
  140.         }
  141.  
  142.         static void SaveDataToFile(Window win, WindowPositionData data, string fileName = null)
  143.         {
  144.             string datafilePath = GetDataFilePath(win, fileName);
  145.             string xml = WindowPositionData.SerializeToXml(data);
  146.             File.WriteAllText(datafilePath, xml);
  147.         }
  148.  
  149.         static string GetDataFilePath(Window win, string filePath = null)
  150.         {
  151.             if (!string.IsNullOrWhiteSpace(filePath))
  152.                 return filePath;
  153.  
  154.             const string DATA_FILE_NAME = "WindowPositionData.xml";
  155.             const string DATA_FILE_FORMAT = "WindowPositionData_{0}.xml";
  156.  
  157.             filePath = DATA_FILE_NAME;
  158.             if (win != null)
  159.                 filePath = string.Format(DATA_FILE_FORMAT, win.GetType().Name);
  160.  
  161.             string dirpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  162.             dirpath = Path.Combine(dirpath, "EOG", GetProcessNameWithoutExtension());
  163.             if (!Directory.Exists(dirpath))
  164.                 Directory.CreateDirectory(dirpath);
  165.  
  166.             return Path.Combine(dirpath, filePath);
  167.  
  168.         }
  169.  
  170.         static string GetProcessNameWithoutExtension()
  171.         {
  172.             using (System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess())
  173.             {
  174.                 string procName = Path.GetFileNameWithoutExtension(current.MainModule.FileName);
  175.                 //remove .vshost suffix used in debugging
  176.                 if (procName.Contains("."))
  177.                 {
  178.                     var parts = procName.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  179.                     procName = parts[0];
  180.                 }
  181.                 return procName;
  182.             }
  183.         }
  184.  
  185.         public static string GetSettingsDirectory()
  186.         {
  187.             string dirpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
  188.             dirpath = Path.Combine(dirpath, "EOG", "IFile");
  189.             if (!Directory.Exists(dirpath))
  190.                 Directory.CreateDirectory(dirpath);
  191.             return dirpath;
  192.         }
  193.  
  194.         static string SerializeToXml(WindowPositionData data)
  195.         {
  196.             if (data == null)
  197.                 throw new ArgumentNullException("data");
  198.  
  199.             return XmlSerialization.Serialize<WindowPositionData>(data);
  200.         }
  201.  
  202.         static WindowPositionData DeserializeFromXml(string xml)
  203.         {
  204.             if (string.IsNullOrEmpty(xml))
  205.                 throw new ArgumentNullException("xml");
  206.  
  207.             return XmlSerialization.Deserialize<WindowPositionData>(xml);
  208.         }
  209.  
  210.         static void GetWindowPosition(Window win)
  211.         {
  212.             WindowPositionData data = new WindowPositionData();
  213.             GetWindowPosition(win, data);
  214.         }
  215.  
  216.         /// <summary>
  217.         /// If the window is more than half off of the screen move it up and to the left
  218.         /// so half the height and half the width are visible, and If the saved window dimensions are larger than the current screen shrink the
  219.         /// window to fit.
  220.         /// </summary>
  221.         public static void SizeToFit(Window win)
  222.         {
  223.             if (win.Height > System.Windows.SystemParameters.VirtualScreenHeight)
  224.             {
  225.                 win.Height = System.Windows.SystemParameters.VirtualScreenHeight;
  226.             }
  227.  
  228.             if (win.Width > System.Windows.SystemParameters.VirtualScreenWidth)
  229.             {
  230.                 win.Width = System.Windows.SystemParameters.VirtualScreenWidth;
  231.             }
  232.  
  233.             if (win.Top + win.Height / 2 > System.Windows.SystemParameters.VirtualScreenHeight)
  234.             {
  235.                 win.Top = System.Windows.SystemParameters.VirtualScreenHeight - win.Height;
  236.             }
  237.  
  238.             if (win.Left + win.Width / 2 > System.Windows.SystemParameters.VirtualScreenWidth)
  239.             {
  240.                 win.Left = System.Windows.SystemParameters.VirtualScreenWidth - win.Width;
  241.             }
  242.  
  243.             //if (win.Top < 0)
  244.             //{
  245.             //  win.Top = 0;
  246.             //}
  247.  
  248.             //if (win.Left < 0)
  249.             //{
  250.             //  win.Left = 0;
  251.             //}
  252.         }
  253.  
  254.         /// <summary>
  255.         /// If the window is more than half off of the screen move it up and to the left
  256.         /// so half the height and half the width are visible, and If the saved window dimensions are larger than the current screen shrink the
  257.         /// window to fit.
  258.         /// </summary>
  259.         public static void SizeToFit(WindowPositionData data)
  260.         {
  261.             if (data.WindowHeight > System.Windows.SystemParameters.VirtualScreenHeight)
  262.             {
  263.                 data.WindowHeight = System.Windows.SystemParameters.VirtualScreenHeight;
  264.             }
  265.  
  266.             if (data.WindowWidth > System.Windows.SystemParameters.VirtualScreenWidth)
  267.             {
  268.                 data.WindowWidth = System.Windows.SystemParameters.VirtualScreenWidth;
  269.             }
  270.  
  271.             if (data.WindowTop + data.WindowHeight / 2 > System.Windows.SystemParameters.VirtualScreenHeight)
  272.             {
  273.                 data.WindowTop = System.Windows.SystemParameters.VirtualScreenHeight - data.WindowHeight;
  274.             }
  275.  
  276.             if (data.WindowLeft + data.WindowWidth / 2 > System.Windows.SystemParameters.VirtualScreenWidth)
  277.             {
  278.                 data.WindowLeft = System.Windows.SystemParameters.VirtualScreenWidth - data.WindowWidth;
  279.             }
  280.  
  281.             if (data.WindowTop < 0)
  282.             {
  283.                 data.WindowTop = 0;
  284.             }
  285.  
  286.             if (data.WindowLeft < 0)
  287.             {
  288.                 data.WindowLeft = 0;
  289.             }
  290.         }
  291.  
  292.         public static void EnsureWindowIsInBounds(Window win)
  293.         {
  294.             var numberofMonitors = System.Windows.Forms.SystemInformation.MonitorCount;
  295.             var allScreens = System.Windows.Forms.Screen.AllScreens;
  296.  
  297.             var winBounds = allScreens[numberofMonitors - 1].Bounds;
  298.  
  299.             //check whether height and width are in bounds
  300.             if (win.Top + win.Height > winBounds.Top + winBounds.Height)
  301.             {
  302.                 win.Top = winBounds.Height - win.Height;
  303.             }
  304.  
  305.             if (win.Left + win.Width > winBounds.Left + winBounds.Width)
  306.             {
  307.                 win.Left = winBounds.Width - win.Width;
  308.             }
  309.         }
  310.         #endregion
  311.  
  312.         public class XmlSerialization
  313.         {
  314.             public static string Serialize<T>(T xmlObject)
  315.             {
  316.                 return Serialize<T>(xmlObject, false);
  317.             }
  318.             public static string Serialize<T>(T xmlObject, bool encodeInBase64)
  319.             {
  320.                 using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
  321.                 {
  322.                     System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
  323.                     System.Xml.Serialization.XmlSerializerNamespaces xmlNamespace = new System.Xml.Serialization.XmlSerializerNamespaces();
  324.                     xmlNamespace.Add(string.Empty, string.Empty);
  325.                     xs.Serialize(memoryStream, xmlObject, xmlNamespace);
  326.                     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
  327.                     if (encodeInBase64)
  328.                         return Convert.ToBase64String(System.Text.ASCIIEncoding.Unicode.GetBytes(encoding.GetString(memoryStream.ToArray())));
  329.                     else
  330.                         return encoding.GetString(memoryStream.ToArray());
  331.                 }
  332.             }
  333.             public static T Deserialize<T>(string xml)
  334.             {
  335.                 return Deserialize<T>(xml, false);
  336.             }
  337.             public static T Deserialize<T>(string xml, bool decodeInBase64)
  338.             {
  339.                 string data = xml;
  340.                 if (decodeInBase64)
  341.                     data = System.Text.ASCIIEncoding.Unicode.GetString(Convert.FromBase64String(xml));
  342.                 System.Xml.Serialization.XmlSerializer xs = System.Xml.Serialization.XmlSerializer.FromTypes(new Type[] { typeof(T) })[0];
  343.                 System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
  344.                 using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encoding.GetBytes(data)))
  345.                 {
  346.                     System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, System.Text.Encoding.UTF8);
  347.                     return (T)xs.Deserialize(memoryStream);
  348.                 }
  349.             }
  350.         }
  351.     }
  352. }
Advertisement
Add Comment
Please, Sign In to add comment