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.vb
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Data
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Imaging
Imports System.Windows.Shapes
Imports Microsoft.Win32
Namespace Windows
Public Partial Class SavePosition
Inherits System.Windows.Window
Public Sub New()
InitializeComponent()
End Sub
Private Sub cmdSave_Click(sender As Object, e As RoutedEventArgs)
WindowPositionHelper.SaveSize(Me)
End Sub
Private Sub cmdRestore_Click(sender As Object, e As RoutedEventArgs)
WindowPositionHelper.SetSize(Me)
End Sub
End Class
Public Class WindowPositionHelper
Public Shared RegPath As String = "Software\MyApp\"
Public Shared Sub SaveSize(win As Window)
Dim key As RegistryKey = Registry.CurrentUser.CreateSubKey(RegPath & win.Name)
key.SetValue("Bounds", win.RestoreBounds.ToString())
End Sub
Public Shared Sub SetSize(win As Window)
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(RegPath & win.Name)
If key IsNot Nothing Then
Dim bounds As Rect = Rect.Parse(key.GetValue("Bounds").ToString())
win.Top = bounds.Top
win.Left = bounds.Left
If win.SizeToContent = SizeToContent.Manual Then
win.Width = bounds.Width
win.Height = bounds.Height
End If
End If
End Sub
End Class
End Namespace
Related examples in the same category