IT学习联盟

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
IT学习联盟 门户 文章 ASP.NET/C# 查看内容

C#判断当前启动程序进程是否存在

2012-8-18 03:03| 发布者: admin| 查看: 632| 评论: 0

System.Threading.Mutex mutex;//注意,此变量要定义为成员变量,而不是局部变量
  bool CheckMultiInstance()
        {
            bool createdNew = true;
            mutex = new System.Threading.Mutex(true, "_TEST_Mutex_", out createdNew);//这种在系统多用户下,每个用户能启动一个程序进程。
mutex = new System.Threading.Mutex(true, "Global\\_TEST_Mutex_", out createdNew);//这种在系统中,不管几个用户,只能存在一个这样的程序进程

            if (!createdNew)
            {
               MessageBox.Show("Program is already running.");
            }
            return createdNew;
        }

        /// <summary>
        /// Is exist same process
        /// </summary>
        /// <returns></returns>
        public static Process GetExistProcess()
        {
            try
            {
                var current = Process.GetCurrentProcess();
                var pArrayy = System.Diagnostics.Process.GetProcessesByName(current.ProcessName);
                if (pArrayy == null || pArrayy.Length == 0)
                {
                    return null;
                }
                foreach (var item in pArrayy)
                {
                    try
                    {
                        if (!item.ProcessName.ToUpper().Contains(current.ProcessNameToUpper()))
                        {
                            continue;
                        }
                        if (item.Id != current.Id && item.MainModule.ModuleName.ToUpper() == current.MainModule.ModuleName.ToUpper())
                        {
                            return item;
                        }
                    }
                    catch (Exception er)
                    {
                        LogHelper.WriteException(er);
                        continue;
                    }
                
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
            }
            return null;
        }
 


Archiver|IT学习联盟| 网站地图

Powered by Discuz! X2.5© 2001-2010 世界学习室 大伟制作

GMT+8, 2018-2-25 05:38 , Processed in 0.101928 second(s), 12 queries .