How can I prevent launching my app multiple times?

后端 未结 10 1834
北荒
北荒 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:07
     if (Process.GetProcesses().Count(p => p.ProcessName == "exe name") > 1)
        {
            foreach (var process in 
     Process.GetProcessesByName("exe name"))
            {
                process.Kill();
            }
        }
    
    0 讨论(0)
  • 2020-12-13 19:08

    what i always using is

    bool checkSingleInstance()
        {
            string procName = Process.GetCurrentProcess().ProcessName;
            // get the list of all processes by that name
    
            Process[] processes = Process.GetProcessesByName(procName);
    
            if (processes.Length > 1)
            {
    
                return true;
            }
            else
            {
                return false;
            }
        }
    
    0 讨论(0)
  • 2020-12-13 19:12

    There is really good topic on that matter. You can find it here: using Mutext.

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题