检查我的Windows应用程序是否正在运行

Sta*_*ker 32 c# winforms

如何检查我的C#Windows应用程序是否正在运行?

我知道我可以检查进程名称,但如果exe更改,则可以更改名称.

有没有办法让哈希键或其他东西使我的应用程序独一无二?

abr*_*pin 39

public partial class App : System.Windows.Application
{
    public bool IsProcessOpen(string name)
    {
        foreach (Process clsProcess in Process.GetProcesses()) 
        {
            if (clsProcess.ProcessName.Contains(name))
            {
                return true;
            }
        }

        return false;
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        // Get Reference to the current Process
        Process thisProc = Process.GetCurrentProcess();

        if (IsProcessOpen("name of application.exe") == false)
        {
            //System.Windows.MessageBox.Show("Application not open!");
            //System.Windows.Application.Current.Shutdown();
        }
        else
        {
            // Check how many total processes have the same name as the current one
            if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
            {
                // If ther is more than one, than it is already running.
                System.Windows.MessageBox.Show("Application is already running.");
                System.Windows.Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 这很脆弱:`IsProcessOpen("application.exe"的名字)``.可执行文件可能在编写源代码的时刻与在用户计算机上运行源代码之间更改了名称.Mutex没有这个问题,也没有假设应用程序是如何运行的. (7认同)

bas*_*rat 21

推荐的方法是使用互斥锁.您可以在此处查看示例:http: //www.codeproject.com/KB/cs/singleinstance.aspx

具体代码:


        /// 
        /// check if given exe alread running or not
        /// 
        /// returns true if already running
        private static bool IsAlreadyRunning()
        {
            string strLoc = Assembly.GetExecutingAssembly().Location;
            FileSystemInfo fileInfo = new FileInfo(strLoc);
            string sExeName = fileInfo.Name;
            bool bCreatedNew;

            Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
            if (bCreatedNew)
                mutex.ReleaseMutex();

            return !bCreatedNew;
        }
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用GUID而不是`sExeName`,它将适用于任何应用程序. (6认同)
  • 如果检查应用程序与正在运行的应用程序相同,则此方法有效. (2认同)