21
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アプリケーションの多重起動を禁止する

Posted at

Mutexで実装してみました。ちゃんと書くとけっこう大変ですね。

static class Program
{
    [STAThread]
    static void Main()
    {
        using (var mutex = new Mutex(false, "YOUR_APPLICATION_NAME_Running"))
        {
            try
            {
                if (mutex.WaitOne(0))
                {
                    Run(mutex);
                }
                else
                {
                    // 起動済みのウィンドウをアクティブにすると親切かも
                    MessageBox.Show("多重起動はできません");
                }
            }
            catch (AbandonedMutexException)
            {
                // new Mutex()~WaitOne()の間で、既に起動中のプロセスが強制終了した
                // この場合もMutexの所有権は取得できているので、起動して問題ない
                Run(mutex);
            }
        }
    }

    static void Run(Mutex mutex)
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
        finally
        {
            // 例外で終了したときにMutexが解放されないのを防ぐため、finallyで行う
            mutex.ReleaseMutex();
        }
    }
}

ちなみに、別のコンストラクタを使った以下の書き方は、参考サイトによると正しくないそうです。
理由が書かれていなかったので、ご存じの方は教えていただけるとうれしいです。
同期周りは難しい…

Mutex m = new Mutex(true, "myApp", out createdNew);

参考

http://stackoverflow.com/questions/646480/is-using-a-mutex-to-prevent-multipule-instances-of-the-same-program-from-running
http://stackoverflow.com/questions/819773/run-single-instance-of-an-application-using-mutex

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?