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

时间:2015-02-02 10:03:16

标签: c# .net 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;
            }
        }
    }
}

但是我遇到了一些问题。

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

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

2 个答案:

答案 0 :(得分: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");
        }
    }
}

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

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

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

答案 1 :(得分:1)

你可以试试下面的片段吗?

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