using System;
using System.IO;
using System.Windows;
using System.Xml.Serialization;
namespace System.Windows
{
/*
public MainWindow()
{
InitializeComponent();
WindowPositionData.LoadWindowPosision(this);
this.Closing += (s, e) => WindowPositionData.SaveWindowPosision(this);
}
*/
///
/// Class used to persist window's position
///
[XmlRoot("WindowPositionData")]
[Serializable]
public class WindowPositionData
{
///
/// True to ignore setting window position on startup, changed in user options
///
public bool IgnoreOnStartup { get; set; }
///
/// True to ignore the main dock layout on startup, changed in user options
///
public bool IgnoreDockLayoutOnStartup { get; set; }
public double WindowTop { get; set; }
public double WindowLeft { get; set; }
public double WindowHeight { get; set; }
public double WindowWidth { get; set; }
public System.Windows.WindowState WindowState { get; set; }
public bool AllValuesZero()
{
return WindowTop <= 0 && WindowLeft <= 0 && WindowHeight <= 0 && WindowWidth <= 0;
}
#region static methods
public static WindowPositionData MainWindowPosition { get; private set; }
public static void LoadWindowPosision(Window win, string fileName = null)
{
WindowPositionData data = GetDataFromFile(win, fileName);
MainWindowPosition = data;
if (!data.IgnoreOnStartup)
{
SetWindowPosition(win, data);
}
}
public static void SaveWindowPosition(Window win, string fileName = null)
{
WindowPositionData data = MainWindowPosition ?? new WindowPositionData();
GetWindowPosition(win, data);
if (MainWindowPosition != null)
{
data.IgnoreOnStartup = MainWindowPosition.IgnoreOnStartup;
}
SaveDataToFile(win, data, fileName);
}
public static void GetWindowPosition(Window win, WindowPositionData data)
{
data.WindowWidth = win.Width;
data.WindowHeight = win.Height;
data.WindowTop = win.Top;
data.WindowLeft = win.Left;
data.WindowState = win.WindowState;
}
public static void SetWindowPosition(Window win, WindowPositionData data)
{
if (data.AllValuesZero())
{
win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
else
{
win.WindowStartupLocation = WindowStartupLocation.Manual;
}
if (data.WindowWidth > 0)
win.Width = data.WindowWidth;
if (data.WindowHeight > 0)
win.Height = data.WindowHeight;
if (data.WindowTop > 0)
win.Top = data.WindowTop;
else
{
if (double.IsNaN(win.Top))
win.Top = 0;
}
win.Left = data.WindowLeft;
//if (data.WindowLeft > 0)
//else
//{
// if (double.IsNaN(win.Left))
// win.Left = 0;
//}
SizeToFit(win);
EnsureWindowIsInBounds(win);
if (data.WindowState != WindowState.Minimized)
{
win.WindowState = data.WindowState;
}
}
static WindowPositionData GetDataFromFile(Window win, string filePath = null)
{
string datafilePath = GetDataFilePath(win, filePath);
try
{
if (File.Exists(datafilePath))
{
return WindowPositionData.DeserializeFromXml(File.ReadAllText(datafilePath));
}
else
return new WindowPositionData();
}
catch
{
return new WindowPositionData();
}
}
static void SaveDataToFile(Window win, WindowPositionData data, string fileName = null)
{
string datafilePath = GetDataFilePath(win, fileName);
string xml = WindowPositionData.SerializeToXml(data);
File.WriteAllText(datafilePath, xml);
}
static string GetDataFilePath(Window win, string filePath = null)
{
if (!string.IsNullOrWhiteSpace(filePath))
return filePath;
const string DATA_FILE_NAME = "WindowPositionData.xml";
const string DATA_FILE_FORMAT = "WindowPositionData_{0}.xml";
filePath = DATA_FILE_NAME;
if (win != null)
filePath = string.Format(DATA_FILE_FORMAT, win.GetType().Name);
string dirpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
dirpath = Path.Combine(dirpath, "EOG", GetProcessNameWithoutExtension());
if (!Directory.Exists(dirpath))
Directory.CreateDirectory(dirpath);
return Path.Combine(dirpath, filePath);
}
static string GetProcessNameWithoutExtension()
{
using (System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess())
{
string procName = Path.GetFileNameWithoutExtension(current.MainModule.FileName);
//remove .vshost suffix used in debugging
if (procName.Contains("."))
{
var parts = procName.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
procName = parts[0];
}
return procName;
}
}
public static string GetSettingsDirectory()
{
string dirpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
dirpath = Path.Combine(dirpath, "EOG", "IFile");
if (!Directory.Exists(dirpath))
Directory.CreateDirectory(dirpath);
return dirpath;
}
static string SerializeToXml(WindowPositionData data)
{
if (data == null)
throw new ArgumentNullException("data");
return XmlSerialization.Serialize(data);
}
static WindowPositionData DeserializeFromXml(string xml)
{
if (string.IsNullOrEmpty(xml))
throw new ArgumentNullException("xml");
return XmlSerialization.Deserialize(xml);
}
static void GetWindowPosition(Window win)
{
WindowPositionData data = new WindowPositionData();
GetWindowPosition(win, data);
}
///
/// If the window is more than half off of the screen move it up and to the left
/// so half the height and half the width are visible, and If the saved window dimensions are larger than the current screen shrink the
/// window to fit.
///
public static void SizeToFit(Window win)
{
if (win.Height > System.Windows.SystemParameters.VirtualScreenHeight)
{
win.Height = System.Windows.SystemParameters.VirtualScreenHeight;
}
if (win.Width > System.Windows.SystemParameters.VirtualScreenWidth)
{
win.Width = System.Windows.SystemParameters.VirtualScreenWidth;
}
if (win.Top + win.Height / 2 > System.Windows.SystemParameters.VirtualScreenHeight)
{
win.Top = System.Windows.SystemParameters.VirtualScreenHeight - win.Height;
}
if (win.Left + win.Width / 2 > System.Windows.SystemParameters.VirtualScreenWidth)
{
win.Left = System.Windows.SystemParameters.VirtualScreenWidth - win.Width;
}
//if (win.Top < 0)
//{
// win.Top = 0;
//}
//if (win.Left < 0)
//{
// win.Left = 0;
//}
}
///
/// If the window is more than half off of the screen move it up and to the left
/// so half the height and half the width are visible, and If the saved window dimensions are larger than the current screen shrink the
/// window to fit.
///
public static void SizeToFit(WindowPositionData data)
{
if (data.WindowHeight > System.Windows.SystemParameters.VirtualScreenHeight)
{
data.WindowHeight = System.Windows.SystemParameters.VirtualScreenHeight;
}
if (data.WindowWidth > System.Windows.SystemParameters.VirtualScreenWidth)
{
data.WindowWidth = System.Windows.SystemParameters.VirtualScreenWidth;
}
if (data.WindowTop + data.WindowHeight / 2 > System.Windows.SystemParameters.VirtualScreenHeight)
{
data.WindowTop = System.Windows.SystemParameters.VirtualScreenHeight - data.WindowHeight;
}
if (data.WindowLeft + data.WindowWidth / 2 > System.Windows.SystemParameters.VirtualScreenWidth)
{
data.WindowLeft = System.Windows.SystemParameters.VirtualScreenWidth - data.WindowWidth;
}
if (data.WindowTop < 0)
{
data.WindowTop = 0;
}
if (data.WindowLeft < 0)
{
data.WindowLeft = 0;
}
}
public static void EnsureWindowIsInBounds(Window win)
{
var numberofMonitors = System.Windows.Forms.SystemInformation.MonitorCount;
var allScreens = System.Windows.Forms.Screen.AllScreens;
var winBounds = allScreens[numberofMonitors - 1].Bounds;
//check whether height and width are in bounds
if (win.Top + win.Height > winBounds.Top + winBounds.Height)
{
win.Top = winBounds.Height - win.Height;
}
if (win.Left + win.Width > winBounds.Left + winBounds.Width)
{
win.Left = winBounds.Width - win.Width;
}
}
#endregion
public class XmlSerialization
{
public static string Serialize(T xmlObject)
{
return Serialize(xmlObject, false);
}
public static string Serialize(T xmlObject, bool encodeInBase64)
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(T));
System.Xml.Serialization.XmlSerializerNamespaces xmlNamespace = new System.Xml.Serialization.XmlSerializerNamespaces();
xmlNamespace.Add(string.Empty, string.Empty);
xs.Serialize(memoryStream, xmlObject, xmlNamespace);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
if (encodeInBase64)
return Convert.ToBase64String(System.Text.ASCIIEncoding.Unicode.GetBytes(encoding.GetString(memoryStream.ToArray())));
else
return encoding.GetString(memoryStream.ToArray());
}
}
public static T Deserialize(string xml)
{
return Deserialize(xml, false);
}
public static T Deserialize(string xml, bool decodeInBase64)
{
string data = xml;
if (decodeInBase64)
data = System.Text.ASCIIEncoding.Unicode.GetString(Convert.FromBase64String(xml));
System.Xml.Serialization.XmlSerializer xs = System.Xml.Serialization.XmlSerializer.FromTypes(new Type[] { typeof(T) })[0];
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(encoding.GetBytes(data)))
{
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, System.Text.Encoding.UTF8);
return (T)xs.Deserialize(memoryStream);
}
}
}
}
}