How can I prevent launching my app multiple times?

后端 未结 10 1839
北荒
北荒 2020-12-13 18:42

I deployed my C# WinForms application using ClickOnce installation. Everything works fine with it (after a lot of work) :), but now I\'m facing a problem:

Whenever

10条回答
  •  伪装坚强ぢ
    2020-12-13 19:12

    In WPF, you can use this code in your App.xaml.cs file:

    private static System.Threading.Mutex _mutex = null;
    
    protected override void OnStartup(StartupEventArgs e)
    {
        string mutexId = ((System.Runtime.InteropServices.GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false).GetValue(0)).Value.ToString();
        _mutex = new System.Threading.Mutex(true, mutexId, out bool createdNew);
        if (!createdNew) Current.Shutdown();
        else Exit += CloseMutexHandler;
        base.OnStartup(e);
    }
    protected virtual void CloseMutexHandler(object sender, EventArgs e)
    {
        _mutex?.Close();
    }
    

    • https://www.c-sharpcorner.com/UploadFile/f9f215/how-to-restrict-the-application-to-just-one-instance/
    • https://social.msdn.microsoft.com/Forums/vstudio/en-US/eced1b92-43c5-405d-84b1-780e774c9d3e/how-can-i-prevent-launching-my-app-multiple-times?forum=wpf

提交回复
热议问题