一、引言
最近发现很多人在论坛中问到如何防止程序被多次运行的问题的,所以这里就记录下来,希望给遇到同样问题的朋友有所参考的,同时也是对自己的一个积累。在介绍具体实现代码之前,我们必须明确解决这个问题的思路是什么的?下面只要分享我的一个思考的这个问题的方式:

1、当我们点击一个exe文件时,此时该exe程序将会运行,我们可以看到该程序的界面,对于计算机而言,就是会在系统上开启一个该程序的进行,这个我们可以通过任务管理器来查看的(当我们点击exe之后,程序运行,系统会创建一个与与程序同名的进程)

2、既然我们要防止程序运行多次,也就是说程序只能运行一次,从操作系统的角度来讲就是该程序的进程只能是唯一的,分析到这里我们自然就想到了,要保证该程序进程只有一个,我们就要判断下该程序进程是否在自己的操作系统上运行了,如果已经运行了一个进程,当我们下次运行exe的时候,此时不是再开启该程序进程,而是退出,弹出一个提示框告诉用户该程序已经运行,如果操作系统没有运行该程序进程,则运行这个程序。

3、从而这个问题就转换为判断该程序进程的数量问题了,此时我们就想.net 有没有提供一个类可以获得该进程名的数量,如果数量大于1则说明该程序已经运行了,小于就表明程序没有运行。如果熟悉.net类库的人肯定知道.net类库中有一个process类,该类的意思就是一个进程的抽象。(有些人就会说,我一开始不知道有这个类那怎么办呢?那就是考验你英文了,因为进程的英文就是process,然而所有编程语言的命名都很通俗易懂,此时就可以用process在msdn上搜索,这样你也就发现这个类了)

4、除了第三点中提出找进程数量的思路外,还有另外一种实现思路就是——我们能不能让运行一个进程的时候,让该进程具有一个变量,该变量是唯一标识该进程,当点击exe文件预创建一个改程序进程时,我们去判断这个变量是否存在,如果存在就说明这个进程已经运行,从而退出本次的程序,并且提示给用户说该程序已经运行。
从上面的分析过程中可以看出,我们解决这个问题的思路就是从进程入手,第三点的思路就是直接从进程数量入手,而第四点思路也是从进程入手,只是做了一个变换罢了,让一个变量来唯一标识一个进程,当变量存在时说明该程序进程也运行了。

二、使用互斥量mutex
弄懂了主要的实现思路之后,下面看代码实现就完全不是问题了,使用互斥量的实现就是第四点的思路的体现,我们用为该程序进程创建一个互斥量mutex对象变量,当运行该程序时,该程序进程就具有了这个互斥的mutex变量,如果再次运行该程序时,通过检查该互斥变量是否存在(来替换检测这个进程是否存在),如果存在则说明程序已运行,否则就没运行。这里需要注意的是:从我的多线程同步的文章大家可以知道,mutex类也可以对线程进行同步,那是不是其他对线程同步的类也可以解决本专题中的问题呢?答案是否定,之所以mutex类可以解决这个问题,是因为mutex类除了可以对线程同步,也可以对进程同步。下面就具体看看实现代码吧:

using system;
using system.threading;
using system.windows.forms;

namespace onlyinstancerunning
{
  static class program
  {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [stathread]
    static void main()
    {
      #region 方法一:使用互斥量
      bool createnew;

      // creatednew:
      // 在此方法返回时,如果创建了局部互斥体(即,如果 name 为 null 或空字符串)或指定的命名系统互斥体,则包含布尔值 true;
      // 如果指定的命名系统互斥体已存在,则为false
      using (mutex mutex = new mutex(true, application.productname, out createnew))
      {
        if (createnew)
        {
          application.enablevisualstyles();
          application.setcompatibletextrenderingdefault(false);
          application.run(new form1());
        }
        // 程序已经运行的情况,则弹出消息提示并终止此次运行
        else
        {
          messagebox.show("应用程序已经在运行中...");
          system.threading.thread.sleep(1000);

          // 终止此进程并为基础操作系统提供指定的退出代码。
          system.environment.exit(1);
        }
      }

      #endregion
    }
  }
}

  三、直接判断进程是否存在的方式来解决这个问题
3.1 判断该程序进程数量的方式
有了上面的思路分析之后,相信大家看下面代码会觉得一目了然,这里就不多解释了,直接看代码:

#region 方法二:使用进程名
      process[] processcollection = process.getprocessesbyname(application.companyname);
      // 如果该程序进程数量大于,则说明该程序已经运行,则弹出提示信息并提出本次操作,否则就创建该程序
      if (processcollection.length >= 1)
      {
        messagebox.show("应用程序已经在运行中。。");
        thread.sleep(1000);
        system.environment.exit(1);
      }
      else
      {
        application.enablevisualstyles();
        application.setcompatibletextrenderingdefault(false);
        // 运行该应用程序
        application.run(new form1());
      }
      #endregion 

  3.2 直接判断程序进程是否存在的方式

using system;
using system.diagnostics;
using system.reflection;
using system.runtime.interopservices;
using system.windows.forms;

namespace way3
{
  static class program
  {
    #region 方法三:使用的win32函数的声明
    /// <summary>
    /// 设置窗口的显示状态
    /// win32 函数定义为:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
    /// </summary>
    /// <param name="hwnd">窗口句柄</param>
    /// <param name="cmdshow">指示窗口如何被显示</param>
    /// <returns>如果窗体之前是可见,返回值为非零;如果窗体之前被隐藏,返回值为零</returns>
    [dllimport("user32.dll")]
    private static extern bool showwindow(intptr hwnd, int cmdshow);

    /// <summary>
    /// 创建指定窗口的线程设置到前台,并且激活该窗口。键盘输入转向该窗口,并为用户改变各种可视的记号。
    /// 系统给创建前台窗口的线程分配的权限稍高于其他线程。
    /// </summary>
    /// <param name="hwnd">将被激活并被调入前台的窗口句柄</param>
    /// <returns>如果窗口设入了前台,返回值为非零;如果窗口未被设入前台,返回值为零</returns>
    [dllimport("user32.dll")]
    private static extern bool setforegroundwindow(intptr hwnd);

    // 指示窗口为普通显示
    private const int ws_shownormal = 1;
    #endregion

    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [stathread]
    static void main()
    {
      #region 方法三:调用win32 api,并激活运行程序的窗口显示在最前端
      // 这种方式在vs调用的情况不成立的,因为在vs中按f5运行的进程为onlyinstancerunning.vshost,从这个进程的命名就可以看出,该进程为onlyinstancerunning进程的宿主进程
      // 关于这个进程的更多内容可以查看:http://msdn.microsoft.com/zh-cn/library/ms185331(v=vs.100).aspx
      // 而直接点onlyinstancerunning.exe运行的程序进程为onlyinstancerunning,
      // 但是我们可以一些小的修改,即currentprocess.processname.replace(".vshose","")此时无论如何都为 onlyinstancerunning

      // 获得正在运行的程序,如果没有相同的程序,则运行该程序
      process process = runninginstance();
      if (process == null)
      {
        application.enablevisualstyles();
        application.setcompatibletextrenderingdefault(false);
        application.run(new form1());
      }
      else
      {
        // 已经运行该程序,显示信息并使程序显示在前端
        messagebox.show("应用程序已经在运行中......");
        handlerunninginstance(process);
      }
      #endregion 
    }

    #region 方法三定义的方法
    /// <summary>
    /// 获取正在运行的程序,没有运行的程序则返回null
    /// </summary>
    /// <returns></returns>
    private static process runninginstance()
    {
      // 获取当前活动的进程
      process currentprocess = process.getcurrentprocess();

      // 根据当前进程的进程名获得进程集合
      // 如果该程序运行,进程的数量大于1
      process[] processcollection = process.getprocessesbyname(currentprocess.processname.replace(".vshost", ""));
      foreach (process process in processcollection)
      {
        // 如果进程id不等于当前运行进程的id以及运行进程的文件路径等于当前进程的文件路径
        // 则说明同一个该程序已经运行了,此时将返回已经运行的进程
        if (process.id != currentprocess.id)
        {
          if (assembly.getexecutingassembly().location.replace("/", "\\") == process.mainmodule.filename)
          {
            return process;
          }
        }
      }

      return null;
    }

    /// <summary>
    /// 显示已运行的程序
    /// </summary>
    /// <param name="instance"></param>
    private static void handlerunninginstance(process instance)
    {
      // 显示窗口
      showwindow(instance.mainwindowhandle, ws_shownormal);

      // 把窗体放在前端
      setforegroundwindow(instance.mainwindowhandle);
    }

    #endregion
  }
}

  3.3 解决3.2实现方式中存在的问题——只能是最小化的窗体显示出来,如果隐藏到托盘中则不能把运行的程序显示出来

using system;
using system.diagnostics;
using system.runtime.interopservices;
using system.windows.forms;

namespace way4
{
  static class program
  {

    #region 方法四:使用的win32函数的声明

    /// <summary>
    /// 找到某个窗口与给出的类别名和窗口名相同窗口
    /// 非托管定义为:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633499(v=vs.85).aspx
    /// </summary>
    /// <param name="lpclassname">类别名</param>
    /// <param name="lpwindowname">窗口名</param>
    /// <returns>成功找到返回窗口句柄,否则返回null</returns>
    [dllimport("user32.dll")]
    public static extern intptr findwindow(string lpclassname, string lpwindowname);

    /// <summary>
    /// 切换到窗口并把窗口设入前台,类似 setforegroundwindow方法的功能
    /// </summary>
    /// <param name="hwnd">窗口句柄</param>
    /// <param name="falttab">true代表窗口正在通过alt/ctrl +tab被切换</param>
    [dllimport("user32.dll ", setlasterror = true)]
    static extern void switchtothiswindow(intptr hwnd, bool falttab);

    ///// <summary>
    ///// 设置窗口的显示状态
    ///// win32 函数定义为:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
    ///// </summary>
    ///// <param name="hwnd">窗口句柄</param>
    ///// <param name="cmdshow">指示窗口如何被显示</param>
    ///// <returns>如果窗体之前是可见,返回值为非零;如果窗体之前被隐藏,返回值为零</returns>
    [dllimport("user32.dll", entrypoint = "showwindow", charset = charset.auto)]
    public static extern int showwindow(intptr hwnd, int ncmdshow);
    public const int sw_restore = 9;
    public static intptr formhwnd;
    #endregion

    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [stathread]
    static void main()
    {
      #region 方法四: 可以是托盘中的隐藏程序显示出来
      // 方法四相对于方法三而言应该可以说是一个改进,
      // 因为方法三只能是最小化的窗体显示出来,如果隐藏到托盘中则不能把运行的程序显示出来
      // 具体问题可以看这个帖子:http://social.msdn.microsoft.com/forums/zh-cn/6398fb10-ecc2-4c03-ab25-d03544f5fcc9
      process currentproc = process.getcurrentprocess();
      process[] processcollection = process.getprocessesbyname(currentproc.processname.replace(".vshost", string.empty));
      // 该程序已经运行,
      if (processcollection.length >= 1)
      {
        foreach (process process in processcollection)
        {
          if (process.id != currentproc.id)
          {
            // 如果进程的句柄为0,即代表没有找到该窗体,即该窗体隐藏的情况时
            if (process.mainwindowhandle.toint32() == 0)
            {
              // 获得窗体句柄
              formhwnd = findwindow(null, "form1");
              // 重新显示该窗体并切换到带入到前台
              showwindow(formhwnd, sw_restore);
              switchtothiswindow(formhwnd, true);
            }
            else
            {
              // 如果窗体没有隐藏,就直接切换到该窗体并带入到前台
              // 因为窗体除了隐藏到托盘,还可以最小化
              switchtothiswindow(process.mainwindowhandle, true);
            }
          }
        }
      }
      else
      {
        application.enablevisualstyles();
        application.setcompatibletextrenderingdefault(false);
        application.run(new form1());
      }
      #endregion
    }
  }
}

  四、程序实现效果
四种实现方式的运行效果都是差不多的,这里就以实现方式一作为演示的,具体实现效果如下图:

五、总结
写这个专题主要是看到原因是看到有些朋友问了这样的问题,所以就总结下具体的实现代码来帮助遇到同样问题的朋友做一个参考,同时也是对自己一个学习的积累和复习。