1. 程式人生 > >winform,同個程式只允許啟動一次

winform,同個程式只允許啟動一次

static class Program
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createNew;
            using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Main());
                }
                else
                {
                    MessageBox.Show("Only one instance of this application is allowed!");
                    Process current = Process.GetCurrentProcess();
                    Process[] processes = Process.GetProcessesByName(current.ProcessName);
                    //遍歷與當前程序名稱相同的程序列表 
                    foreach (Process process in processes)
                    {
                        //如果例項已經存在則忽略當前程序 
                        if (process.Id != current.Id)
                        {
                            //保證要開啟的程序同已經存在的程序來自同一檔案路徑
                            if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                            {
                                ShowWindowAsync(process.MainWindowHandle, 1);  //呼叫api函式,正常顯示視窗
                                SetForegroundWindow(process.MainWindowHandle); //將視窗放置最前端
                            }
                        }
                    }
                }
            }
        }
    }