How can I prevent launching my app multiple times?

霸气de小男生 提交于 2019-11-27 11:44:08

问题


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 I click on the application shortcut in the Start menu, a new instance starts. I need to avoid this.

What can I do to prevent multiple launches?


回答1:


At program startup check if same process is already running:

using System.Diagnostics;

static void Main(string[] args)
{
   String thisprocessname = Process.GetCurrentProcess().ProcessName;

   if (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)
      return;           
}



回答2:


Use this code:

[STAThread]
static void Main() 
{
   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))
   {
      if(!mutex.WaitOne(0, false))
      {
         MessageBox.Show("Instance already running");
         return;
      }

      Application.Run(new Form1());
   }
}

from The Misunderstood Mutex




回答3:


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




回答4:


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



回答5:


There are times **Mutex** is not working in some areas. Like using in console application. So I tried using WMI Query.

Try this and it will work.

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!isStillRunning())
            {
               Application.Run(new Form1());
             }
             else {
                 MessageBox.Show("Previous process still running.",
                    "Application Halted", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                 Application.Exit();
             }      
        }

        //***Uses WMI Query
        static bool isStillRunning() {
            string processName = Process.GetCurrentProcess().MainModule.ModuleName;
            ManagementObjectSearcher mos = new ManagementObjectSearcher();
            mos.Query.QueryString = @"SELECT * FROM Win32_Process WHERE Name = '" + processName + @"'";
            if (mos.Get().Count > 1)
            {
               return true;
            }
            else
               return false;
        }

Hope it helps.




回答6:


When starting you application, main always calls Application.Run(). Look in your STAThread-Main method and before Application.Run test, if there are running instances of your .exe.

Process p = Process.GetProcesses();
//check for your .exe

See this post here.




回答7:


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



回答8:


solution in Windows form application Prohibit again run application(reopen application).

1- first add Class RunAlready.cs

2-Call method processIsRunning() with Name Process from RunAlready.cs in Program.cs

Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tirage.MainStand
{
static class Program
{

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        PublicClass.Class.RunAlready RunAPP = new PublicClass.Class.RunAlready();
        string outApp = RunAPP.processIsRunning("Tirage.MainStand");

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MainStand_FrmLogin fLogin = new MainStand_FrmLogin();
        if (outApp.Length == 0)
        {

            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new MainStand_masterFrm());

            }
        }
        else MessageBox.Show( "Instance already running");

      }
    }
 }

class RunAlready:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PublicClass.Class
{
  public  class RunAlready
    {
      public  string processIsRunning(string process)
        {
        string xdescription = "";
        System.Diagnostics.Process[] processes =
            System.Diagnostics.Process.GetProcessesByName(process);
        foreach (System.Diagnostics.Process proc in processes)
        {
            var iddd = System.Diagnostics.Process.GetCurrentProcess().Id;
            if (proc.Id != System.Diagnostics.Process.GetCurrentProcess().Id)
            {
                xdescription = "Application Run At time:" + proc.StartTime.ToString() + System.Environment.NewLine;
                xdescription += "Current physical memory : " + proc.WorkingSet64.ToString() + System.Environment.NewLine;
                xdescription += "Total processor time : " + proc.TotalProcessorTime.ToString() + System.Environment.NewLine;
                xdescription += "Virtual memory size : " +         proc.VirtualMemorySize64.ToString() + System.Environment.NewLine;
            }
        }


        return xdescription;
    }
}
}



回答9:


 if (Process.GetProcesses().Count(p => p.ProcessName == "exe name") > 1)
    {
        foreach (var process in 
 Process.GetProcessesByName("exe name"))
        {
            process.Kill();
        }
    }



回答10:


Using Mutex is the way to go because guessing process names is full of flaws and niggles. Check out this really nice illustration



来源:https://stackoverflow.com/questions/15115241/how-can-i-prevent-launching-my-app-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!