讓程序以單一實例運行

 

 #region 讓程序以單一實例運行
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        private const int SW_RESTORE = 9;

        /// <summary>
        /// 在 main() 中調用:if (!Common.RunSingleInstance()) return;
        /// </summary>
        /// <returns></returns>
        public static bool RunSingleInstance()
        {
            string proc = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(proc);
            if (processes.Length > 1)
            {
                Process p = Process.GetCurrentProcess();
                int n = 0;
                if (processes[0].Id == p.Id)
                {
                    n = 1;
                }
                IntPtr hWnd = processes[n].MainWindowHandle;
                if (IsIconic(hWnd))
                {
                    ShowWindowAsync(hWnd, SW_RESTORE);
                }
                SetForegroundWindow(hWnd);
                return false;
            }
            return true;
        }
        #endregion

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章