Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Windows Forms MDI でよく実装する子フォームの制御処理

0
Posted at

はじめに

備忘録です。久々に MDI を触ったので、書き残しておきます。

環境

  • Visual Studio 2022
  • .NET Framework 4.8.1

MDI とは

1 つの親フォームの中に、複数の子フォームを開いて管理する UI 方式です。古い Office ソフトなどで使用されていました。

20260425_1500_00.png

制御処理

それでは、よく実装する子フォームの制御処理を列挙していきます。

1. フォームを重複生成しない画面表示

private void ShowForm<T>() where T : Form, new()
{
    var existing = _mainForm.MdiChildren.OfType<T>().FirstOrDefault();
    if (existing != null)
    {
        // 既に表示済の場合、アクティブ化する
        existing.WindowState = FormWindowState.Normal;
        existing.Activate();
        return;
    }

    // 生成
    var form = new T { MdiParent = _mainForm };
    form.Show();
}

2. すべて最小化

private void MinimizeAll()
{
    foreach (var child in _mainForm.MdiChildren)
    {
        child.WindowState = FormWindowState.Minimized;
    }
}

3. すべて元に戻す

private void RestoreAll()
{
    foreach (var child in _mainForm.MdiChildren)
    {
        child.WindowState = FormWindowState.Normal;
    }
}

4. すべて閉じる

private void CloseAll()
{
    foreach (var child in _mainForm.MdiChildren.ToArray())
    {
        child.Close();
    }
}

5. 左にドッキング

private void DockLeft()
{
    // スクロールバーが表示されるのを防ぐため、オフセット値で少し余白を空ける
    int offsetHeight = 54;

    var active = _mainForm.ActiveMdiChild;
    if (active is null)
    {
        return;
    }

    active.WindowState = FormWindowState.Normal;
    var client = _mainForm.ClientSize;
    active.Bounds = new Rectangle(
        0,
        0,
        active.Width,
        client.Height - offsetHeight
    );
}

6. 右にドッキング

private void DockRight()
{
    // スクロールバーが表示されるのを防ぐため、オフセット値で少し余白を空ける
    int offsetX = 6;
    int offsetHeight = 54;

    var active = _mainForm.ActiveMdiChild;
    if (active is null)
    {
        return;
    }

    active.WindowState = FormWindowState.Normal;
    var client = _mainForm.ClientSize;
    active.Bounds = new Rectangle(
        client.Width - active.Width - offsetX,
        0,
        active.Width,
        client.Height - offsetHeight
    );
}

おわりに

MDI もいつのまにか見なくなりましたね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?