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
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;
}
}