LoginSignup
1
4

More than 5 years have passed since last update.

[WPF] ウィンドウ位置の保存、復元

Posted at

開発環境

  • Visual Studio 2017
  • WPF 4.5.1

概要

  1. Settings.settingsを利用してパラメータを保持する。
  2. イベントを利用して、適宜処理を行う。 2017-05-30_18h36_59.png

サンプルコード(該当コードのみ)

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    /// <summary>
    /// OnSourceInitialized
    /// </summary>
    /// <param name="e">EventArgs</param>
    protected override void OnSourceInitialized(EventArgs e)
    {
        base.OnSourceInitialized(e);

        LoadWindowPlacement();
    }

    /// <summary>
    /// OnClosing
    /// </summary>
    /// <param name="e">CancelEventArgs</param>
    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);

        if (!e.Cancel)
        {
            SaveWindowPlacement();
        }
    }

    /// <summary>
    /// Window位置の復元
    /// </summary>
    void LoadWindowPlacement()
    {
        Properties.Settings.Default.Reload();

        var bounds = Properties.Settings.Default.Bounds;
        Left = bounds.Left;
        Top = bounds.Top;
        Width = bounds.Width;
        Height = bounds.Height;

        WindowState = Properties.Settings.Default.WindowState;
    }

    /// <summary>
    /// Window位置の保存
    /// </summary>
    void SaveWindowPlacement()
    {
        Properties.Settings.Default.WindowState = WindowState == WindowState.Minimized ? WindowState.Normal : WindowState; // 最小化は保存しない
        Properties.Settings.Default.Bounds = RestoreBounds;

        Properties.Settings.Default.Save();
    }
}
1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4