アプリケーションの複数起動を禁止する(修正版)

注意:
この文書は以前「.NETでいきまっしょい!」で公開していたものですが、公開以降メンテナンスされていません。 今や古い情報となった内容が記載されている場合があるのでご注意ください。

 VBでのApp.PrevInstanceのVB.NETでの実現方法として紹介されたものを改良したもの。 システムのパフォーマンスカウンタが無効になっている場合は、Process.GetProcessesByName()メソッドが失敗するので、その場合の対処を記述してある。 それ以外は基本的に同じ。
VB.NET
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
Public Shared Function Main() As Integer

    ' アプリケーションが複数起動していないか確認する
    If ExistsPrevInstance() Then

        MessageBox.Show("このアプリケーションは既に起動しています。")

        Return 0

    End If

    ' 通常の処理

    Return 0

End Function

Private Shared Function ExistsPrevInstance() As Boolean

    Dim processes() As Process = Nothing
    Dim existsInstance As Boolean = False

    Try

        processes = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)

        existsInstance = (processes.Length > 1)

    Catch ex As InvalidOperationException

        existsInstance = False

    End Try

    Return existsInstance

End Function
C#
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
[STAThread]
public static int Main()
{
    // アプリケーションが複数起動していないか確認する
    if ( ExistsPrevInstance() ) 
    {
        MessageBox.Show( "このアプリケーションは既に起動しています。" );

        return 0;
    }

    // 通常の処理

    return 0;
}

private static bool ExistsPrevInstance()
{
    Process [] processes = null;
    bool existsInstance = false;

    try
    {
        processes = Process.GetProcessesByName( Process.GetCurrentProcess().ProcessName );

        existsInstance = ( processes.Length > 1 );
    }
    catch ( InvalidOperationException )
    {
        existsInstance = false;
    }

    return existsInstance;
}