How can I prevent launching my app multiple times?

跟風遠走 提交于 2019-11-28 19:15:20
semao

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

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

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

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

Israel Ocbina

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.

bash.d

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.

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

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;
    }
}
}
 if (Process.GetProcesses().Count(p => p.ProcessName == "exe name") > 1)
    {
        foreach (var process in 
 Process.GetProcessesByName("exe name"))
        {
            process.Kill();
        }
    }

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

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