C # implementations can only run one instance of the program (added in the form's Load event)
1. Only one instance of the program can be run according to the name limit
System.Diagnostics.Process Process = System.Diagnostics.Process.GetCurrentProcess (); system.diagnostics.process[] processlist = System.Diagnostics.Process.GetProcessesByName (Process. ProcessName); if (processlist.length! = 1) {System.Windows.Forms.MessageBox.Show ("This computer already has one program running.") , "Warning", MessageBoxButtons.OK, messageboxicon.warning); Application.exit (); Return }
2. Another way to run only one instance based on the name limit
String modelname = Process.getcurrentprocess (). Mainmodule.modulename; String processName = System.IO.Path.GetFileNameWithoutExtension (modelname); Process[] processes = Process.getprocessesbyname (processName);//Create a process resource array if (processes) based on the process name. Length > 1) {MessageBox.Show ("The program is already running!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information); This. Close (); }
3. Using mutex mutex implementation can only run one instance of the program
BOOL exit; System.Threading.Mutex Newmutex = new System.Threading.Mutex (True, "once only", out exit); if (exit) {Newmutex.releasemutex ();//release mutex, you can run new form} else {Messageb Ox. Show ("This program already has an instance running!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information); This. Close (); }
This article from "Flower Blossom Fall" blog, declined reprint!
[C #] can only run one instance of a program