2012年1月18日 星期三

[C#] 防止多開的2個處理方法

方法1:
 //直接砍 Process
  System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
            if (p.Length > 1)
            {
                for (int i = 0; i < p.Length; i++)
                {
                    p[i].Kill();
                }
            }

方法2:

//宣告
        [DllImport("kernel32.dll", EntryPoint = "CreateMutexA", SetLastError = true)]
        public static extern IntPtr CreateMutex(IntPtr securityAttributes, bool initialOwner, string name);
        [DllImport("kernel32.dll", EntryPoint = "ReleaseMutex", SetLastError = true)]
        public static extern IntPtr ReleaseMutex(IntPtr handle);

        public static bool IsMutexDataExist(string name)
        {
            bool returnValue = false;
            int ERROR_ALREADY_EXISTS = 183;
            IntPtr handle = CreateMutex(IntPtr.Zero, true, name);
            if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
            {
                returnValue = true;
            }
            ReleaseMutex(handle);
            return returnValue;
        }

//使用方法
             if (IsMutexDataExist("BetWorldAuthServer") == true)
            {
                //MessageBox.Show("已經在執行中", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Environment.Exit(0);
            }