只充许运行一个应用程序实例

来源:互联网 发布:linux sudo chown r 编辑:程序博客网 时间:2024/06/06 20:24

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace AutoUpdate
{
    static class Program
    {
        private static Mutex mutex = null;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
           
            #region 方法一
            if (CreateMutex())
            {
                Application.Run(new FrmUpdate());
                ReleasMutex();
            }
            else
            {
                MessageBox.Show("程序已运行");
                HandleRunningInstance();
            }
            #endregion

            #region 方法二
            //Process p = GetRunningInstance();
            //if (p != null) //已经有应用程序副本执行
            //{
            //    HandleRunningInstance(p);
            //}
            //else //启动第一个应用程序
            //{
            //    Application.Run(new MainForm());
            //}

            ////简洁的调用为,
            ////if (HandleRunningInstance() == false)
            ////{
            ////    Application.Run(new FrmUpdate());
            ////}
            #endregion
        }

        static bool CreateMutex()
        {
            //return CreateMutex(Assembly.GetEntryAssembly().FullName);
            return CreateMutex(AssemblyProduct + AssemblyProduct);
        }

        static bool CreateMutex(string name)
        {
            bool result = false;
            mutex = new Mutex(true, name, out result);
            return result;
        }
        static void ReleasMutex()
        {
            if (mutex != null)
                mutex.Close();
        }

        //使用GetRunningInstance静态方法获取应用程序进程实例,如果没有匹配进程,返回Null值,
        public static Process GetRunningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess(); //获取当前进程
            //获取当前运行程序完全限定名
            string currentFileName = currentProcess.MainModule.FileName;
            //获取进程名为ProcessName的Process数组。
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            //遍历有相同进程名称正在运行的进程
            foreach (Process process in processes)
            {
                if (process.MainModule.FileName == currentFileName)
                {
                    if (process.Id != currentProcess.Id) //根据进程ID排除当前进程
                        return process;//返回已运行的进程实例
                }
            }
            return null;
        }
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]       //前端显示窗体
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        //定义类成员辅助变量,
        private const int WS_SHOWNORMAL = 1;

        //以上的方法声明为私有,对其进一步包装,HandleRunningInstance静态方法
        //为获取应用程序句柄,设置应用程序为前台运行,并返回bool值。
        public static bool HandleRunningInstance(Process instance)
        {
            //确保窗口没有被最小化或最大化
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            //设置为foreground window
            return SetForegroundWindow(instance.MainWindowHandle);
        }

        //对上面的方法创建一个重载版本,使调用代码更加简洁
        public static bool HandleRunningInstance()
        {
            Process p = GetRunningInstance();
            if (p != null)
            {
                HandleRunningInstance(p);
                return true;
            }
            return false;
        }

        #region 属性 (返回程序集的产品名及公司名)
        public static string AssemblyProduct
        {
            get
            {
                // 获取此程序集上的所有 Product 属性
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(
                    typeof(AssemblyProductAttribute), false);
                // 如果 Product 属性不存在,则返回一个空字符串
                if (attributes.Length == 0)
                    return "";
                // 如果有 Product 属性,则返回该属性的值
                return ((AssemblyProductAttribute)attributes[0]).Product;
            }
        }

        public static string AssemblyCompany
        {
            get
            {
                // 获取此程序集上的所有 Company 属性
                object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(
                    typeof(AssemblyCompanyAttribute), false);
                // 如果 Company 属性不存在,则返回一个空字符串
                if (attributes.Length == 0)
                    return "";
                // 如果有 Company 属性,则返回该属性的值
                return ((AssemblyCompanyAttribute)attributes[0]).Company;
            }
        }
        #endregion
    }
}

原创粉丝点击