确保只运行winform应用程序的单个实例

时间:2015-08-14 12:45:48

标签: winforms

我想确保只运行我的winform应用程序的单个实例。有没有什么方法可以通过visual studio 2008来实现它,而不是在代码背后执行它

1 个答案:

答案 0 :(得分:0)

static void Main()         {

        if (PriorProcess() != null)
        {

            MessageBox.Show("Another instance of the app is already running.");
            return;
        }
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());


    }

    public static Process PriorProcess()
    // Returns a System.Diagnostics.Process pointing to
    // a pre-existing process with the same name as the
    // current one, if any; or null if the current process
    // is unique.
    {
        Process curr = Process.GetCurrentProcess();
        Process[] procs = Process.GetProcessesByName(curr.ProcessName);
        foreach (Process p in procs)
        {
            if ((p.Id != curr.Id) &&
                (p.MainModule.FileName == curr.MainModule.FileName))
                return p;
        }
        return null;
    }