LoginSignup
0
0

More than 5 years have passed since last update.

WinFormsアプリで複数開けるようにしたメインフォームをすべて閉じたときにアプリケーションを終了する簡単な方法

Posted at

はじめに

Windows フォームアプリケーションで、複数のフォーム(メインウインドウ)を自由に開いて、かつすべて閉じたときにアプリケーションを終了させるようにします。Multiple Top-level Interface (MTI) というやつです。

コード

フォームは、次の画面のような、Buttonコントロール1つ (buttonOpenという名前) を配置。

image.png
System.Windows.Forms.Application クラスが、便利に計らってくれます。

Program.cs
using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            (new Form1()).Show();
            Application.Run(); // <- Form とアプリケーション(メッセージポンプ)終了を連動させず、Application.Exit()で終了メッセージを受け取るまで動作させる。

            //Application.Run(new Form1());
        }
    }
}

MainForm.cs
using System;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            (new Form1()).Show();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            if (Application.OpenForms.Count == 1) // <- 開いているメインフォームの数
            {
                Application.Exit();
            }
        }
    }
}

結果

デバッグ実行させ、任意のフォーム上のOpenボタンをクリックすると、フォームが増殖していきます。右上の×ボタンを使ってフォームをすべて閉じると、アプリケーションがおわってデバッガが終了します。
image.png

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