Method 1: Use thread mutex variables. Define mutex variables to determine whether an instance is running. Change the Main() function in the program.cs file to the following code:
Note: In the program, the statement 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, and when this method returns, if a local mutex or a specified naming system mutex is created, the boolean value runone is true; false if the specified naming system mutexe already exists. Named mutexes are system-wide. Method 2: Use the way of judging the process, before we run the program, we find whether there is a process with the same name in the process, and the running position is also the same process. Apply the Process class in the System.Diagnostics namespace in C# to implement it, the main code is as follows: 1. Add a function to the program.cs file as follows:
2. Change the Main () function to the following code:
Method 3: Global atomic method, before creating a program, first check the global atomic table to see if there is a specific atom A (added at the time of creation), and stop creating it when it exists, indicating that the program has run an instance; If it doesn't exist, run the program and want to add a specific atom A to the global atomic table; When exiting the program, remember to release a specific atom A, otherwise it will not be released until the computer is turned off. The C# implementation is as follows: 1. Declare the 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 atoms [System.Runtime.InteropServices.DllImport("kernel32.dll")] public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom); Delete atoms 2. Modify the Main() function as follows:
3. Add the following code to the FormClosed event: GlobalDeleteAtom(GlobalFindAtom("jiaao_test")); Delete atomic "jiaao_test" --------------------------------------*-------*--------*----------------------------------------------- The above is the basic general idea of creating a mutually exclusive program, and I personally think that the first method is the simplest. |