当前位置:编程学习 > asp >>

wpf只运行一个实例

在winform下,只运行一个实例只需这样就可以:
1. 首先要添加如下的namespace:
using System.Threading;
2. 修改系统Main函数,大致如下:
        bool bCreatedNew;     
        //Create a new mutex using specific mutex name
        Mutex m =new Mutex( false, "myUniqueName", out bCreatedNew );
        if( bCreatedNew )
            Application.Run(new yourFormName());
在wpf中如何做呢?
我在微软论坛发帖之后,有高手提出了如下的解决办法,我试验之后,此法可行,就贴出来和大家分享。有人还有其他解决办法,可以写出来一起探讨:
首先 引用Microsoft.VisualBasic
然后新建一个类 single
   public  class single:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
    {
       App a;
       public single()
       {
           this.IsSingleInstance = true;
       }
       protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
       {
           a = new App();
           a.InitializeComponent();
           a.Run();
           return false;
       }
       protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
       {
           base.OnStartupNextInstance(eventArgs);
           a.activate();
       }
    }

app.cs
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Window1 w = new Window1();
            w.Show();
        }
        public void activate()
        {
            MainWindow.Activate();
        }
        private void Application_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
       
        }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
         
        }
        private void Application_Exit(object sender, ExitEventArgs e)
        {
   
        }
    }
app.g.cs
        [System.STAThreadAttribute()]
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public static void Main(string [] a ) {
            single s = new single();
            s.Run(a);  
        }
刚开始运行的时候,虽然实现了再次点击不会有新实例,但是却每次都实例了两个窗口的情况。去掉 app.xaml中StartupUri属性就OK了。


作者:fwj380891124
补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,