1

アプリケーションがありますが、現在はシングルトンアプリケーションではありません。実行時に別のインスタンスが終了しないように、シングルトンアプリケーションにするのが好きです。

これが可能な場合は、いくつかのサンプルコードを返信してください。

4

3 に答える 3

3

ここにいくつかの良いサンプルアプリケーションがあります。以下は1つの可能な方法です。

public static Process RunningInstance() 
{ 
    Process current = Process.GetCurrentProcess(); 
    Process[] processes = Process.GetProcessesByName (current.ProcessName); 

    //Loop through the running processes in with the same name 
    foreach (Process process in processes) 
    { 
        //Ignore the current process 
        if (process.Id != current.Id) 
        { 
            //Make sure that the process is running from the exe file. 
            if (Assembly.GetExecutingAssembly().Location.
                 Replace("/", "\\") == current.MainModule.FileName) 

            {  
                //Return the other process instance.  
                return process; 

            }  
        }  
    } 
    //No other instance was found, return null.  
    return null;  
}


if (MainForm.RunningInstance() != null)
{
    MessageBox.Show("Duplicate Instance");
    //TODO:
    //Your application logic for duplicate 
    //instances would go here.
}

他の多くの可能な方法。代替案については、例を参照してください。

最初の1つ。

二つ目。

三つ目。

于 2011-06-22T09:02:42.463 に答える
1

私が知っているアプローチは次のとおりです。プログラムは、名前付きミューテックスを開こうとする必要があります。そのミューテックスが存在する場合は終了し、そうでない場合はミューテックスを作成します。しかし、これは「別のインスタンスが実行時に終了しない」という条件と矛盾しているようです。とにかく、多分これも役に立ちました

于 2011-06-22T08:36:04.970 に答える