首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#判断现阶段启动程序进程是否存在

2012-08-28 
C#判断当前启动程序进程是否存在 System.Threading.Mutex mutex//注意,此变量要定义为成员变量,而不是局

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

 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;

        }

 

热点排行