如何检查我的程序是否已经 运行?

How can I check if my program is already running?

我试过这样做:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
using DannyGeneral;

namespace mws
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                if (IsApplicationAlreadyRunning() == true)
                {
                    MessageBox.Show("The application is already running");
                }
                else
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
            }
            catch (Exception err)
            {
                Logger.Write("error " + err.ToString());
            }
        }
        static bool IsApplicationAlreadyRunning()
        {
            string proc = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(proc);
            if (processes.Length > 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

但我遇到了一些问题。

首先,当我在 Visual Studio 中加载我的项目然后 运行 我的程序时,它正在检测我的项目的 vshost.exe 文件,例如:我的 project.vshost

我希望它会检测我的程序是否 运行 仅当我是 运行 程序时仅当它找到 .exe 例如:我的 project.exe 不是vshost.

看看使用互斥量。

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    static void Main() {
        if(mutex.WaitOne(TimeSpan.Zero, true)) {
            try
            {
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new Form1());
            }
            finally
            {
             mutex.ReleaseMutex();
            }
        } else {
            MessageBox.Show("only one instance at a time");
        }
    }
}

如果我们的应用是 运行,WaitOne 将 return 为 false,您会看到一个消息框。

正如@Damien_The_Unbeliever 正确指出的那样,您应该为您编写的每个应用程序更改互斥锁的 Guid!

来源:http://sanity-free.org/143/csharp_dotnet_single_instance_application.html

你能试试下面的代码片段吗?

private static void Main(string[] args)
    {

        if (IsApplicationAlreadyRunning())
        {
            Console.Write("The application is already running");
        }
        else
        {
            Console.Write("The application is not running");
        }
        Console.Read();
    }

     static bool IsApplicationAlreadyRunning()
    {
        return Process.GetProcesses().Count(p => p.ProcessName.Contains(Assembly.GetExecutingAssembly().FullName.Split(',')[0]) && !p.Modules[0].FileName.Contains("vshost")) > 1;
    }