使用内核对象Mutex可以防止同一个进程运行两次

使用内核对象Mutex可以防止同一个进程运行两次

用互斥法实现防止程序重复运行,使用内核对象Mutex可以防止同一个进程运行两次。注意:是名称相同的进程,而不是exe,因为exe程序可以改名。

using System.Threading;

public partial class App : Application
{
    private Mutex myMutex;
    private bool mutexWasCreated;
    private bool requestInitialOwnership = true;
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        myMutex = new Mutex(requestInitialOwnership, "CanbeAnything ", out mutexWasCreated);
        if (!mutexWasCreated)
        {
            MessageBox.Show("应用已打开");
            Environment.Exit(0);
        }
    }
}