フォームのクローズ、アプリケーションの終了をキャンセルする - C#

フォームが閉じられるのをキャンセルしたり、アプリケーションの終了をキャンセルしたいことがあります。
フォームが閉じられる際にFormClosingイベントが呼び出されるので、引数のFormClosingEventArgsのCancelプロパティにTrueを代入することで、フォームを閉じる処理を中止できます。

例1

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FormClosing
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
    {
      e.Cancel = true;
    }
  }
}

実行結果

アプリケーションを実行するとフォームが表示されますが、フォーム右上の「×」ボタンをクリックしてもフォームは閉じられません。

例2

コード

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FormClosing
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
    {
      DialogResult dr = MessageBox.Show("終了して良いですか?", "終了", 
        MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

      if (dr == System.Windows.Forms.DialogResult.Yes) {
      }
      else {
        e.Cancel = true;
      }
    }
  }
}

実行結果

アプリケーションを実行します。フォームが表示されます。


フォームの閉じるボタンを押してフォームを閉じる操作をすると、確認ダイアログが表示されます。ダイアログの[はい]ボタンを押すとフォームが閉じられますが、[いいえ]ボタンを押した場合はフォームを閉じる操作がキャンセルされます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-04-27
iPentec all rights reserverd.