Save Window Position to Registry


   
  

<Window x:Class="Windows.SavePosition"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SavePosition" Height="300" Width="300" >
  <StackPanel Margin="10">
    <Button Click="cmdSave_Click">Save Position</Button>
    <Button Click="cmdRestore_Click">Restore Position</Button>
  </StackPanel>
</Window>
//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
 
namespace Windows
{
    public partial class SavePosition : System.Windows.Window
    {
        public SavePosition()
        {
            InitializeComponent();
        }

        private void cmdSave_Click(object sender, RoutedEventArgs e)
        {
            WindowPositionHelper.SaveSize(this);
        }

        private void cmdRestore_Click(object sender, RoutedEventArgs e)
        {
            WindowPositionHelper.SetSize(this);
        }
    }
    public class WindowPositionHelper
    {
        public static string RegPath = @"SoftwareMyApp";
        
        public static void SaveSize(Window win)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey(RegPath + win.Name);
            key.SetValue("Bounds", win.RestoreBounds.ToString());            
        }

        public static void SetSize(Window win)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RegPath + win.Name);
            if (key != null)
            {
                Rect bounds = Rect.Parse(key.GetValue("Bounds").ToString());

                win.Top = bounds.Top;
                win.Left = bounds.Left;
                if (win.SizeToContent == SizeToContent.Manual)
                {
                    win.Width = bounds.Width;
                    win.Height = bounds.Height;
                }
            }
        }
    }

}