Double-click a WinForm program to open an interface, that is, an instance running a program. When you double-click multiple times, multiple program interfaces will appear. Sometimes we only need to allow the program to run only one instance at a time. There are many implementation methods.
I. Process mutex
Principle: by obtaining the list of system processes, if there is a duplicate name, it indicates that the program is running, and the newly running process exits at this time;
Implementation: The static method GetProcessesByName (string processName) of the System. Diagnostics. Process class)
Process[] ps = Process.GetProcessesByName( (ps != && ps.Length >
Write it in the Main method; judge that Length is greater than 1 because it is also in the process list after it is started. Length = 1 at the first startup;
Advantage: the code is simple;
Disadvantages: The program will mistakenly identify it as a feature (for example, many software programs have update.exe); you can copy multiple exe files and create different names to run multiple instances;
Ii. Shared locks (files and registries)
Principle: when running a program, create a shared value in a public location (for example, creating a file in a fixed directory or creating a value in a fixed registry location ), this value is deleted when you exit the program. If the present value is already present during running, it indicates that the program is already running, and the newly running process exits;
Implementation: omitted;
Advantage: the logic is easy to understand;
Disadvantage: if the program does not exit normally and the shared value is not deleted, the program cannot be started again;
Iii. Thread mutex
Principle: create a process mutex with a unique identifier. Check whether the mutex exists at startup. If yes, it indicates a duplicate process;
Implementation: Use System. Threading. Mutex
Main( Attribute guid_attr = Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), guid == System.Threading.Mutex(, guid, ( ==
Advantage: Only one process can be run in the same program;
Disadvantage: None
NOTE: If different users log on to windows at the same time, they can still run one instance. If you want different users to run only one instance, the guid variable above needs to be prefixed with "Global \", see the http://www.csharpwin.com/csharpspace/12748r5312.shtml for details