The C program allows only one instance to run in several ways

  • 2020-05-12 03:05:18
  • OfStack

In this article, I'll show you how to use C# to create a system in which only one instance of the program can run.
Mutual exclusion of programs is usually implemented in the following ways, using the C# language:
Method 1:
Use thread mutexes. Determine if an instance is running by defining mutexes.
Change the Main() function in program.cs to the following code:

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace NetTools
{
    static class Program
    {
        [DllImport("user32.dll")]
        private static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
        [DllImport("user32.dll")]
        private static extern bool FlashWindowEx(int pfwi);
        /// <summary>
        ///  The application's main entry point. 
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool runone;
            System.Threading.Mutex run = new System.Threading.Mutex(true, "single_test", out runone);
            if (runone)
            {
                run.ReleaseMutex();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                FrmRemote frm = new FrmRemote();
                int hdc = frm.Handle.ToInt32(); // write to ...
                Application.Run(frm);
                IntPtr a = new IntPtr(hdc);
            }
            else
            {
                MessageBox.Show(" It's already running 1 So that's an example. ");
                //IntPtr hdc = new IntPtr(1312810); // read from...
                //bool flash = FlashWindow(hdc, true);
            }
        }
    }
}

Instruction: System. Threading. Mutex run = new System. Threading. Mutex(true, "single_test", out runone); To create a mutex variable run, where "single_test" is the mutex name. When this method returns, the Boolean runone is true if a local mutex or a named system mutex is created. false if the specified naming system mutex already exists. The named mutexes are system-wide.
Method 2: we use the method of judging the process, before running the program, we find out whether there is a process with the same name in the process, and the running location is also the same process, if there is no running the program, it will not run.
1. Add the function in the program.cs file as follows:

public static System.Diagnostics.Process RunningInstance() 
{ 
System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess(); 
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses(); 
foreach (System.Diagnostics.Process process in processes) // Find a process with the same name  
{ 
if (process.Id != current.Id) // Ignore the current process  
{ // Verify that the same process is running in the same location 1 sample . 
if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"/") == current.MainModule.FileName) 
  { //Return the other process instance. 
   return process; 
  } 
} 
} //No other instance was found, return null. 
return null; 
} 

2. Change the Main () function to the following code:

static void Main() 
{ 
if(RunningInstance()==null) 
{ 
Application.EnableVisualStyles(); 
Application.SetCompatibleTextRenderingDefault(false); 
Application.Run(new Form1()); 
} 
else 
{ 
MessageBox.Show(" It's already running 1 So that's an example. "); 
} 
} 

Method 3: global atom method. Before creating the program, check the global atom table to see if there is a specific atom A (added when creating), and stop creating when there is, indicating that the program has run one instance. If it doesn't exist, run the program and add specific atoms to the global atom table. Remember to release a specific A atom when you exit the program, otherwise it will not be released until the program is shut down. C# is implemented as follows:
1. Declare WinAPI function interface

[System.Runtime.InteropServices.DllImport("kernel32.dll")] 
public static extern UInt32 GlobalAddAtom(String lpString); // Add atoms  
[System.Runtime.InteropServices.DllImport("kernel32.dll")] 
public static extern UInt32 GlobalFindAtom(String lpString); // Find the atomic  
[System.Runtime.InteropServices.DllImport("kernel32.dll")] 
public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom); // Delete atoms 

2. Modify the Main() function as follows:

static void Main() 
{ 
if (GlobalFindAtom("jiaao_test") == 77856768) // No atom found "jiaao_test" 
{ 
GlobalAddAtom("jiaao_test"); // Add atoms "jiaao_test" 
Application.EnableVisualStyles(); 
Application.SetCompatibleTextRenderingDefault(false); 
Application.Run(new Form1()); 
} 
else 
{ 
MessageBox.Show(" It's already running 1 So that's an example. "); 
} 
} 

3. Add the following code in the FormClosed event:
jiaao_test GlobalDeleteAtom (GlobalFindAtom (" ")); // delete atom "jiaao_test"
--------------------------------------*-------*--------*-----------------------------------------------
For the basic general idea of creating mutually exclusive programs, I think the first method is the simplest.

Related articles: