欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net4.0中wpf单例启动

程序员文章站 2022-07-13 22:23:40
...

添加Microsoft.VisualBasic引用,头引用

using Microsoft.VisualBasic.ApplicationServices;

打开App.xaml.cs文件,将文件修改为如下

class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            SingleInstanceApp a = new SingleInstanceApp();
            a.Run(args);
        }
    }

    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : System.Windows.Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            base.OnStartup(e);
            InitializeComponent();
        }
    }

    public class SingleInstanceApp : WindowsFormsApplicationBase
    {
        App win = null;
        public SingleInstanceApp()
        {
            this.IsSingleInstance = true;
        }

        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
        {
            win = new App();
            win.Run();
            return false;
        }

        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            foreach (System.Windows.Window _win in win.Windows)
            {
                if (_win.Visibility == System.Windows.Visibility.Visible)
                {
                    _win.Activate();
                }
            }
        }
    }

  编译下,vs会告知有2个入口函数,定位到App.g.cs的main函数,直接删除掉就可以了~~以上代码通用,无需修改任何东西..当然,要写入自己的个性需求则自己改~~

转载于:https://www.cnblogs.com/viki117/archive/2012/12/04/2800889.html