C#/WPF 只允许一个实例程序运行并将已运行程序置顶

使用用互斥量(System.Threading.Mutex):
    同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。

实例代码:

    /// 
    /// App.xaml 的交互逻辑
    /// 
    public partial class App : Application
    {
        [DllImport("user32.dll ")]
        //设置窗体置顶
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        private static Mutex _m = null;
        private static string currentProcess = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
        /// 
        /// 只允许运行一个实例
        /// 
        /// 
        /// true:已经存在实例 false:不存在实例
        public static bool CheckRunOneInstance(string mutexName = null)
        {

            bool result = false;
            bool mutexWasCreated = false;
            try
            {
                bool requestInitialOwnership = true;
                if (mutexName == null)
                    mutexName = currentProcess;
                _m = new Mutex(requestInitialOwnership, mutexName, out mutexWasCreated);
                if (!mutexWasCreated)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return result;
        }

        /// 
        /// 有程序运行,设置焦点
        /// 
        private void Focus()
        {
            foreach (Process process in Process.GetProcesses())
            {
                try
                {
                    if (process.ProcessName.ToLower() != currentProcess.ToLower())
                        continue;
                    IntPtr hwnd = process.MainWindowHandle;
                    if (hwnd != IntPtr.Zero)
                    {
                        SetForegroundWindow(hwnd);
                        ShowWindow(hwnd, 2);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            if(CheckRunOneInstance())
            {
                Focus();
                System.Windows.Application.Current.Shutdown();
                return;
            }
            else
            {
                new MainWindow().Show();
            }
        }
    }

实例链接:

https://download.csdn.net/download/lvxingzhe3/88668552

你可能感兴趣的:(WPF,C#,c#,开发语言)