none
WPF之单例模式 RRS feed

  • 问题

  • 1、为了实现单例模式,在App类中添加了如下代码,使用了信号量,但是为什么返回值isNew一直为true

    public partial class App : Application
        {
            protected override void OnStartup(StartupEventArgs e)
            {
                base.OnStartup(e);
                bool isNew=false;
                Mutex mutex = new Mutex(true, "MySingleInstance", out isNew);
                if(!isNew)
                {
                    ActivateOtherWindow();
                    Shutdown();
                }
                GC.KeepAlive(isNew);
            }

            private static void ActivateOtherWindow()
            {
                var other = Win32Api.FindWindow(null, "MainWindow");
                if (other != IntPtr.Zero)
                {
                    Win32Api.SetForegroundWindow(other);
                    if (Win32Api.IsIconic(other))
                        Win32Api.OpenIcon(other);
                }
            }
        }
    2019年10月9日 2:46

答案

  • private Mutex mutex = null;

    private void CheckSingleInstanceAndStartMainApp(string title)
            {
                bool isNew = false;
                if (null == mutex)
                    mutex = new Mutex(true, "PowerPixel", out isNew);
                if (!isNew)
                {
                    ActiveAndShowToFront(title);
                    Environment.Exit(0);//强制退出,不会有弹框提示
                }
            }

            private void ActiveAndShowToFront(string titleName)
            {
                //s1:通过WAPi:FindWindow获取运行实例的句柄
                //或者事先保存实例,传递过来           
                IntPtr hwnd = Win32Api.FindWindow(null, titleName);
                if (hwnd != IntPtr.Zero)
                {
                    Win32Api.SetForegroundWindow(hwnd);
                    if (Win32Api.IsIconic(hwnd))
                        Win32Api.OpenIcon(hwnd);
                }
            }
    • 已标记为答案 heater 2019年10月9日 6:35
    2019年10月9日 6:35

全部回复

  • mutex不能被回收
    2019年10月9日 3:32
  • private Mutex mutex = null;

    private void CheckSingleInstanceAndStartMainApp(string title)
            {
                bool isNew = false;
                if (null == mutex)
                    mutex = new Mutex(true, "PowerPixel", out isNew);
                if (!isNew)
                {
                    ActiveAndShowToFront(title);
                    Environment.Exit(0);//强制退出,不会有弹框提示
                }
            }

            private void ActiveAndShowToFront(string titleName)
            {
                //s1:通过WAPi:FindWindow获取运行实例的句柄
                //或者事先保存实例,传递过来           
                IntPtr hwnd = Win32Api.FindWindow(null, titleName);
                if (hwnd != IntPtr.Zero)
                {
                    Win32Api.SetForegroundWindow(hwnd);
                    if (Win32Api.IsIconic(hwnd))
                        Win32Api.OpenIcon(hwnd);
                }
            }
    • 已标记为答案 heater 2019年10月9日 6:35
    2019年10月9日 6:35