65.9K
CodeProject 正在变化。 阅读更多。
Home

C#中的单一实例控件组件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.08/5 (10投票s)

2003年4月15日

2分钟阅读

viewsIcon

107284

downloadIcon

2

一个单实例控制组件,用于检查您的应用程序是否已经在系统上运行。

引言

本文介绍一个单实例控制组件,用于检查您的应用程序是否已经在系统上运行。您可以使用此组件来检查特定应用程序是否正在运行,或者避免您的应用程序在系统上运行多个实例。 有许多方法可以防止您的应用程序运行多个实例,例如使用复杂的 Mutex 类方法或一些非托管代码。

在这里,我使用了一个简单的 Process 类来检查特定进程是否正在运行。 让我们首先讨论 InstanceControl 组件。 InstanceControl 类继承自 .NET Framework 的 Component 类,该组件具有一个名为 IsAnyInstanceExist() 的方法,该方法检查系统上是否正在运行特定进程,并返回状态为 true/false

  • 命名空间: InstConLib
  • 类: InstanceControl
  • 成员
    • InstanceControl() (构造函数,接受进程名称)
    • IsAnyInstanceExist() (检查进程并返回一个 bool 值)

组件成员的简要说明

  1. InstanceControl(string)InstanceControl 组件的构造函数。 构造函数接受一个字符串参数,该参数是进程名称,并将其存储在成员变量中。
  2. InstanceControl 组件的 IsAnyInstanceExist() 方法通过检查进程是否正在运行来返回 true/false。 此方法使用 Process 类(别名 System.Diagnostics.Process)和 GetProcessesByName() 方法,该方法反过来返回具有该名称正在运行的进程数组。
using System;
using System.Diagnostics;
using System.ComponentModel;

namespace InstConLib { 
/* InstanceControlLib Class controls the instance */

  public class InstanceControl: Component
  {
    private string stProcName=null;
    /*constructor which holds the application name*/
    public InstanceControl(string ProcName)
    {
      stProcName=ProcName;
    }
    public bool IsAnyInstanceExist()
    {  /*process class GetProcessesByName() checks for particular
      process is currently running and returns array of processes
      with that name*/
      Process[] processes = Process.GetProcessesByName(stProcName);
      
        if(processes.Length != 1)
          return false; /*false no instance exist*/
        else 
          return true; /*true mean instance exist*/
    }
  } /*end of class*/
}/*end of namespace*/

将上述内容编译为组件库以生成一个 .dll 文件。 然后,您可以在不同的客户端中使用此组件,例如 WinForms、WebForms 或控制台应用程序。 我使用了一个简单的控制台应用程序来使用此组件。 客户端程序调用 InstanceControl 组件并使用其方法。 在此示例中,我使用了该组件的两个实例。 一个将检查未运行的进程,另一个将检查系统中正在运行的进程。

以下是客户端应用程序的代码片段

//InstClient.cs 

using System;
using InstConLib;
public class InstClient
{
  public static void Main()
  { 
   //First Object which looks for testApp.exe process  

   //remember its not neccessary to give extention of process

   InstConLib.InstanceControl in1 = new InstConLib.InstanceControl("testApp");
   if(in1.IsAnyInstanceExist())
    Console.WriteLine("Alreading one instance is running");
   else
    Console.WriteLine("No Instance running"); 
    //Second Object which looks for Explorer.exe process  

    //remember its not neccessary to give extention of process

    InstConLib.InstanceControl in2 = 
       new InstConLib.InstanceControl("Explorer");

   if(in2.IsAnyInstanceExist())
     Console.WriteLine("Alreading one instance is running");
   else
     Console.WriteLine("No Instance running");
 }
}

输出

D:\vstudio>InstClient
No Instance running
Alreading one instance is running
© . All rights reserved.