アプリケーションを強制終了する

アプリケーションを強制終了するコードを紹介します。

概要

EnvironmentクラスのExitメソッドを用いると、アプリケーションを強制終了できます。第一引数にはOSに渡す終了コードを指定します。正常終了した場合は0を渡すため、多くの場合0を渡すことが多いです。エラーでアプリケーションを強制終了する場合は0以外の値を渡します。

メモ
強制終了ではない、アプリケーション終了のコードについてはこちらの記事を参照してください。

定義

public static void Exit (int exitCode);

書式

Environment.Exit((終了コード));

プログラム例

コンソールアプリケーションを作成します。下記のコードを記述します。

コード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationTerminate
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Start");
      Environment.Exit(0x8020);
      Console.WriteLine("Penguin");
    }
  }
}

実行結果

Start

"Penguin"の文字列は表示されず、Environment.Exit()メソッドの呼び出し時点でアプリケーションが終了します。

比較コード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationTerminate
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Start");
      System.Windows.Forms.Application.Exit();
      Console.WriteLine("Penguin");
    }
  }
}

実行結果

Start
Penguin

"Penguin"の文字列が表示されます。Application.Exit()メソッドの呼び出しでは、呼び出した時点ではアプリケーションは終了されません。

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2012-04-27
Copyright © 1995–2025 iPentec all rights reserverd.