Force Single Instance with Mutex handling restart application

前端 未结 4 2140
[愿得一人]
[愿得一人] 2021-01-25 12:04

I have a problem when i want use mutex to force single instance of my program.

I a winform App with a WebBrowser Control. I need to autorestart if certain conditions ar

4条回答
  •  忘掉有多难
    2021-01-25 12:24

    Single instance apps are well supported by the framework. It supports goodies such as disabling it on-the-fly, what you need here, and getting a notification when another instance is started. You'll want to use that to give your first instance the focus. Rewrite your Program.cs code like this:

    using System;
    using System.Windows.Forms;
    using Microsoft.VisualBasic.ApplicationServices;   // NOTE: add reference to Microsoft.VisualBasic
    
    namespace WindowsFormsApplication1 {
        class Program : WindowsFormsApplicationBase {
            public Program() {
                EnableVisualStyles = true;
                MainForm = new Form1();
                IsSingleInstance = true;
            }
            public static void Main(string[] args) {
                Instance = new Program();
                Instance.Run(args);
            }
            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
                // Nicety, focus the single instance.
                Instance.MainForm.Activate();
            }
            public static void Restart() {
                // What you asked for.  Use Program.Restart() in your code
                Instance.IsSingleInstance = false;
                Application.Restart();
            }
            private static Program Instance;
        }
    }
    

提交回复
热议问题