LoginSignup
2
2

More than 5 years have passed since last update.

割と手軽にFormの座標・サイズを復元するクラス

Last updated at Posted at 2015-09-12

手軽にFormの座標・サイズを復元するクラス

FormSizeSaver.cs
using Codeplex.Data;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

/// <summary>
/// フォームの大きさ、座標を記録する機能を付加します
/// </summary>
public class FormSizeSaver
{
  private static readonly string SaveFilePath = "form_size_init.json";

  /// <param name="target">Boundsを記憶するフォーム</param>
  public FormSizeSaver(Form target)
  {
    // Loadイベントが呼ばれる前に設定する必要がある
    // Showイベントを対象にしても動く
    target.Load += target_Load;
    target.FormClosed += target_FormClosed;
  }

  void target_Load(object sender, EventArgs e)
  {
    Form target = sender as Form;
    if (target == null) return;

    if (!File.Exists(SaveFilePath)) return;

    using (StreamReader sr = new StreamReader(SaveFilePath))
    {
      var json = DynamicJson.Parse(sr.ReadToEnd());
      Rectangle rect = json.Deserialize<Rectangle>();
      target.Bounds = rect;
    }
  }

  void target_FormClosed(object sender, FormClosedEventArgs e)
  {
    Form target = sender as Form;
    if (target == null) return;

    using (StreamWriter sr = new StreamWriter(SaveFilePath))
    {
      sr.WriteLine(DynamicJson.Serialize(target.Bounds));
    }
  }
}

Loadで設定ファイルがアレば復元して、
FormClosedで設定ファイルを書き出しているだけ。

使い方

Form1.cs
public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
    new FormSizeSaver(this);
  }
}

使用するフォームを表示する前に登録するだけ。
使用する側が一文で機能を追加できるのがメリット。

使用ライブラリ

neue cc - DynamicJson - C# 4.0のdynamicでスムーズにJSONを扱うライブラリ
http://neue.cc/2010/04/30_256.html

2
2
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
2
2