C# WPF

重写Startup方法

        /// <summary>
        /// 重写Startup方法
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            // 创建一个互斥对象
            Mutex mutex = new Mutex(true, "单实例程序Mutex", out bool IsNewInstans);
            // 判断是否存在
            if (!IsNewInstans)
            {
                // 查找窗体、显示到前台
                IntPtr intPtr = FindWindowW(null, "MainWindow");
                if (intPtr != IntPtr.Zero)
                {
                    SetForegroundWindow(intPtr);
                }// 退出
                Shutdown();
            }
        }  

导入两个WinAPI函数

        // 找到窗体
        //  FindWindowW F1 在MSDN Doc中查找
        //  HWND FindWindowW(
        //  LPCWSTR lpClassName,
        //  LPCWSTR lpWindowName
        //);
        [DllImport("User32", CharSet = CharSet.Unicode)]
        static extern IntPtr FindWindowW(string lpClassName, string lpWindowName);

        // 显示到前台
        // SetForegroundWindow F1 在MSDN Doc中查找
        // BOOL SetForegroundWindow(
        // HWND hWnd
        // );
        [DllImport("User32", CharSet = CharSet.Unicode)]
        static extern Boolean SetForegroundWindow(IntPtr hWnd);

通过FindWindowW函数可以查找到函数是否存在,然后再通过SetForegroundWindow函数将窗体显示到前台来。 

  作者:Jeremy.Wu
  出处:https://www.cnblogs.com/jeremywucnblog/
  本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/jeremywucnblog/p/12666593.html