WPF避免軟件重複打開的方法

 //===============================================================方法1==有效
        //private static System.Threading.Mutex mutex;
        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    mutex = new System.Threading.Mutex(true, "WpfApp666");
        //    if (mutex.WaitOne(0, false))
        //    {
        //        base.OnStartup(e);
        //    }
        //    else
        //    {
        //        MessageBox.Show("程序已經在運行!", "提示");
        //        this.Shutdown();
        //    }
        //}

        //================================================================方法2==無效
        //[DllImport("user32")]
        //private static extern int SetForegroundWindow(IntPtr hwnd);
        //[DllImport("user32.dll")]
        //private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    IntPtr parenthWnd = FindWindow(null, System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
        //    if (parenthWnd != IntPtr.Zero)
        //    {
        //        //選中當前的句柄窗口
        //        SetForegroundWindow(parenthWnd);
        //        Application.Current.Shutdown();
        //        return;
        //    }
        //    base.OnStartup(e);
        //}
        //================================================================方法3==有效==最終選用
        //System.Threading.Mutex mutex;

        //public App()
        //{
        //    this.Startup += new StartupEventHandler(App_Startup);
        //}

        //void App_Startup(object sender, StartupEventArgs e)
        //{
        //    bool ret;
        //    mutex = new System.Threading.Mutex(true, "WpfApp666", out ret);

        //    if (!ret)
        //    {
        //        MessageBox.Show("已有一個程序實例運行");
        //        Environment.Exit(0);
        //    }
        //}

//===============================================方法4==有效

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Process[] pro = Process.GetProcesses();
            int n = pro.Where(p => p.ProcessName.Equals("WpfApp666")).Count();
            if (n > 1)
            {
                Application.Current.Shutdown();
                return;
            }
        }

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