c prevents code collection sharing from being run multiple times

  • 2020-05-17 06:17:44
  • OfStack

Method 1


class Program
  {
    [STAThread]
    static void Main(string[] args)
    {
      // Prevents the program from running multiple times 
      if (!OneInstance.IsFirst("MyTest"))
      {
        Console.WriteLine(" warning : The program is running !  Please do not open the program repeatedly ! It can be found in the system bar in the lower right corner !");
        return;
      }
      Console.WriteLine(" In operation ");
      Console.ReadLine();
    }
  }
  public static class OneInstance
  {
    ///<summary>
    /// Determine if the program is running  
    ///</summary>
    ///<param name="appId"> The program name </param>
    ///<returns> If the program is number one 1 Secondary run return True, Otherwise returns False</returns>
    public static bool IsFirst(string appId)
    {
      bool ret = false;
      if (OpenMutex(0x1F0001, 0, appId) == IntPtr.Zero)
      {
        CreateMutex(IntPtr.Zero, 0, appId);
        ret = true;
      }
      return ret;
    }
    [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr OpenMutex(
      uint dwDesiredAccess, // access 
      int bInheritHandle,  // inheritance option 
      string lpName     // object name 
      );
    [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr CreateMutex(
      IntPtr lpMutexAttributes, // SD 
      int bInitialOwner,            // initial owner 
      string lpName              // object name 
      );
  }

Method 2


string MnName = Process.GetCurrentProcess().MainModule.ModuleName;
 // Returns the filename of the specified path string without an extension 
String Pname = Path.GetFileNameWithoutExtension(MnName);
Process[] myprocess = Process.GetProcessesByName(Pname);
if (myprocess.Length > 1)
{
  MessageBox.Show("yici", "tishi", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
  //Application.EnableVisualStyles();
  ////Application.SetCompatibleTextRenderingDefault(false);
  //Application.Run(new Form1());
}

Methods 3

Original text is as follows (/ / www. ofstack. com article / 41179. htm)

Often we will have the requirement that the application only run 1 entity. Usually, we double-click an exe file to run an entity of the program, double-click the exe file once, and then run another entity of the application. Take the QQ games for example, one PC can only run one QQ game hall (although I've heard of double-open plug-ins before).

Can our program disable multiple booting like QQ? The answer is yes. Here is a simple implementation: Mutex(mutual exclusion).

Mutex(mutual exclusion, mutually exclusive) is a class in.Net Framework that provides synchronous access across multiple threads. It is very similar to the Monitor class in that they each have only one thread that can hold a lock. While the operating system can recognize the mutual exclusion with a name, we can give the mutual exclusion a unique name and add one such mutex before the program starts. This checks the existence of the named mutex each time the program starts. If it exists, the application exits.


static class Program
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      bool createdNew;
      // The system recognizes named mutexes, so it can be used to disable the application from starting twice 
      // The first 2 Three parameters can be set to the name of the product :Application.ProductName

      // Each time the application is started, the name is validated as SingletonWinAppMutex Is the mutual exclusion of 
      Mutex mutex = new Mutex(false, "SingletonWinAppMutex", out createdNew);
      
      // If run, it is displayed at the front end 
      //createdNew == false , indicating that the program has run 
      if (!createdNew)
      {
        Process instance = GetExistProcess();
        if (instance != null)
        {
          SetForegroud(instance);
          Application.Exit();
          return;
        }
      }
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MainForm());
    }

    /// <summary>
    ///  Check to see if the program is running 
    /// </summary>
    /// <returns></returns>
    private static Process GetExistProcess()
    {
      Process currentProcess = Process.GetCurrentProcess();
      foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
      {
        if ((process.Id != currentProcess.Id) && 
          (Assembly.GetExecutingAssembly().Location == currentProcess.MainModule.FileName))
        {
          return process;
        }
      }
      return null;
    }

    /// <summary>
    ///  Make the program front end display 
    /// </summary>
    /// <param name="instance"></param>
    private static void SetForegroud(Process instance)
    {
      IntPtr mainFormHandle = instance.MainWindowHandle;
      if (mainFormHandle != IntPtr.Zero)
      {
        ShowWindowAsync(mainFormHandle, 1);
        SetForegroundWindow(mainFormHandle);
      }
    }

    [DllImport("User32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("User32.dll")]
    private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
  }

After my test, it is still relatively easy to use, but there is a problem, if you do not log out, with another user to enter, then the program can not be judged to have run. So it's limited to a single user environment, which is still not perfect.


class Program
  {
    [STAThread]
    static void Main(string[] args)
    {
      // Prevents the program from running multiple times 
      if (!OneInstance.IsFirst("MyTest"))
      {
        Console.WriteLine(" warning : The program is running !  Please do not open the program repeatedly ! It can be found in the system bar in the lower right corner !");
        return;
      }
      Console.WriteLine(" In operation ");
      Console.ReadLine();
    }
  }
  public static class OneInstance
  {
    ///<summary>
    /// Determine if the program is running  
    ///</summary>
    ///<param name="appId"> The program name </param>
    ///<returns> If the program is number one 1 Secondary run return True, Otherwise returns False</returns>
    public static bool IsFirst(string appId)
    {
      bool ret = false;
      if (OpenMutex(0x1F0001, 0, appId) == IntPtr.Zero)
      {
        CreateMutex(IntPtr.Zero, 0, appId);
        ret = true;
      }
      return ret;
    }
    [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr OpenMutex(
      uint dwDesiredAccess, // access 
      int bInheritHandle,  // inheritance option 
      string lpName     // object name 
      );
    [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr CreateMutex(
      IntPtr lpMutexAttributes, // SD 
      int bInitialOwner,            // initial owner 
      string lpName              // object name 
      );
  }


Related articles: