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

Hel*_*shi 5 .net c# winforms

我试着这样做:

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我遇到了一些问题.

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

而且我希望只有在我运行程序时它才会检测我的程序是否正在运行,只有当它找到.exe例如:我的project.exe而不是vshost.

fla*_*ayn 17

看一下使用互斥锁.

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我们的应用程序正在运行,WaitOne将返回false,您将收到一个消息框.

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

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

  • 可能是值得加入的上方和GUID低于指出一个新的应为您将这些代码中的每个应用程序生成一个讨厌的意见.否则,一旦有几个人有C&等静压这个代码到他们的项目,并没有想过这个问题,你有一个*类*的程序,其中只有一个实例可以随时运行. (2认同)
  • @Damien_The_Unbeliever 或者更好地使用应用程序名称本身。`Mutex mutex = new Mutex(true, Assembly.GetEntryAssembly().GetName().Name, out createdNew);` (2认同)