代码改变世界

限制程序只能有一个实例

2010-12-02 16:16  ※森林小居※  阅读(287)  评论(0)    收藏  举报

/// <summary>
        /// 限制程序只能有一个实例
        /// </summary>
        /// <returns></returns>
        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;
        }