程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#判斷當前啟動程序進程是否存在

C#判斷當前啟動程序進程是否存在

編輯: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;
        }
 


作者:haylhf

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved