c#防止用戶打開多個實例

在程序運行多個實例時激活的是第一個實例,使其獲得焦點,並在前端顯示.

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

namespace GO_JS
{
    static class Program
    {

        [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;
        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Process instance = RunningInstance();
            if (instance == null)
            {
                Form1 frm = new Form1();
                Application.Run(new Form1());
            }
            else
            {
                HandleRunningInstance(instance);
            }
        }
        public static Process RunningInstance()
        {
            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)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);//顯示,可以註釋掉
            SetForegroundWindow(instance.MainWindowHandle);//放到前端
        }
    }
}

 

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