LoginSignup
30
31

More than 5 years have passed since last update.

C#: ウィンドウの位置・サイズ・最大化状態を保存する

Last updated at Posted at 2012-12-26

※WinFormsの場合です。WPFではプロパティ名やイベントハンドラが異なると思います。

プロジェクトのプロパティで、下記のように設定します。
デフォルト値はフォームのプロパティから拾ってください。

アプリケーション設定

フォームのコードを以下のようにします。

private void MainWindow_Load(object sender, EventArgs e)
{
    // ウィンドウの位置・サイズを復元
    Bounds = Properties.Settings.Default.Bounds;
    WindowState = Properties.Settings.Default.WindowState;
}

private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
    // ウィンドウの位置・サイズを保存
    if (WindowState == FormWindowState.Normal)
        Properties.Settings.Default.Bounds = Bounds;
    else
        Properties.Settings.Default.Bounds = RestoreBounds;

    Properties.Settings.Default.WindowState = WindowState;

    Properties.Settings.Default.Save();
}

マルチディスプレイの場合も動作確認しています。
Boundsを先に復元するのがミソだと思います。

Windows 7では画面左半分・右半分に最大化することができますが、
これは単にウィンドウサイズの変更で実装されているようで、特別扱いは必要なさそうです。
※ これが正しく保存されないアプリをときどき見かけるので、何かある気もしますが…

なお、最小化状態も保存されます。
これがユーザーの混乱を招くようなら、WindowState == FormWindowState.Minimized の場合は保存しないといいと思います。

他のサイトではPropertyBindingを使用する方法がありましたが、
やたらと挙動不審になるので私はあきらめました。

30
31
4

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
30
31