如何防止启动我的应用程序多次?(How can I prevent launching my app

2019-07-20 16:15发布

我使用ClickOnce安装部署我的C#WinForms应用程序。 一切工作正常使用它(大量的工作之后):),但我现在面临一个问题:

每当我点击开始菜单的应用程序快捷方式,一个新的实例启动。 我需要避免这种情况。

我能做些什么来防止发射多?

Answer 1:

在程序启动时检查是否同一进程已经运行:

using System.Diagnostics;

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

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


Answer 2:

使用此代码:

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

从被误解的互斥



Answer 3:

实在是对这个问题很好的话题。 你可以在这里找到它: 使用Mutext 。



Answer 4:

在WPF中,您可以在使用此代码App.xaml.cs文件:

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


Answer 5:

有次**Mutex**不工作在一些区域。 像使用控制台应用程序。 所以,我尝试使用WMI查询

试试这个,它会工作。

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

希望能帮助到你。



Answer 6:

当你启动应用程序,主要总是调用Application.Run() 看看你的STAThread-Main方法和之前Application.Run测试,如果有您的.exe的运行实例。

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

见这个在这里发表。



Answer 7:

我一直使用的是

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


Answer 8:

在Windows窗体应用程序的解决方案再次限度时禁止运行的应用程序(重新申请)。

1-第一添加类RunAlready.cs

2呼叫方法processIsRunning()与名称流程从Program.cs中RunAlready.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");

      }
    }
 }

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


Answer 9:

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


Answer 10:

使用Mutex是去猜测,因为进程名是充满缺陷和niggles的方式。 看看这个非常好的例证



文章来源: How can I prevent launching my app multiple times?