How to create single instance WPF Application that restores the open window when an attempt is made to open another instance?

前端 未结 2 1886
梦毁少年i
梦毁少年i 2020-12-13 15:55

Sorry it the title is hard to understand. I wasn\'t sure how to word it.

I have an application that should only be allowed to run one instance per user session. If t

2条回答
  •  情歌与酒
    2020-12-13 16:53

    I removed the tag StartupUri from the App.xaml file.

    Change the Build Action of App.xaml, from ApplicationDefinition to Page (You can change it on the property window).

    Add a reference to Microsoft.VisualBasic (namespace to WindowsFormsApplicationBase).

    On the class App.xaml.cs, put this code:

    public partial class App : Application
    {
        App()
        {
            InitializeComponent();
        }
    
        [STAThread]
        static void Main()
        {
            SingleInstanceManager manager = new SingleInstanceManager();
            manager.Run(new[] {"teste"});
        }
    }
    
    public class SingleInstanceManager : WindowsFormsApplicationBase
    {
        SingleInstanceApplication app;
    
        public SingleInstanceManager()
        {
            this.IsSingleInstance = true;
        }
    
        protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            // First time app is launched
            app = new SingleInstanceApplication();
            app.Run();
            return false;
        }
    
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            // Subsequent launches
            base.OnStartupNextInstance(eventArgs);
            app.Activate();
        }
    }
    
    public class SingleInstanceApplication : Application
    {
        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            base.OnStartup(e);
    
            // Create and show the application's main window
            MainWindow window = new MainWindow();
            window.Show();
        }
    
        public void Activate()
        {
            // Reactivate application's main window
    
            this.MainWindow.WindowState = WindowState.Normal;
            this.MainWindow.Activate();
        }
    }
    

    I hope it helps :D

提交回复
热议问题