I will introduce two mainstream methods.
Method 1: UseMutexTo
1.First, add the followingNamespace:
UsingSystem. Threading;
2.Modify systemMainFunction, which is roughly as follows:
BoolBcreatednew;
// Create a new mutex using specific mutex name
Mutex M =NewMutex (False, "Myuniquename ",OutBcreatednew );
If(Bcreatednew)
Application. Run (NewYourformname ());
As shown in the preceding code, note thatMutexWhen naming, it should not be too simple to preventProgramOfMutexTo achieve the expected results.
Method 2: UseProcessTo
1.First, add the followingNamespace:
UsingSystem. diagnostics;
UsingSystem. reflection;
2.Add the following functions:
Public StaticProcess runninginstance ()
{
Process current = process. getcurrentprocess ();
Process [] processes = process. getprocessesbyname (current. processname );
// Loop through the running processes in with the same name
Foreach(ProcessInProcesses)
{
// Ignore the current process
If(Process. ID! = Current. ID)
{
// Make sure that the process is running from the EXE file.
If(Assembly. getexecutingassembly (). Location. Replace ("/", "\") = current. mainmodule. filename)
{
// Return the other process instance.
ReturnProcess;
}
}
}
// No other instance was found, return null.
Return Null;
}
3.Modify systemMainFunction, which is roughly as follows:
If(Runninginstance () =Null)
Application. Run (NewYourformname ());
As shown in the preceding code, note that when determining whether the process module File Name is equalCodeIs optional. If only one program exists in the file system, the above method is acceptable; otherwise, do not delete this part of code.
in terms of efficiency and simplicity, the previous method is the best and I like it. The latter method is slow, next, you can use processname to search the system, Process This is not what I want. Although the file directory is added to the end for judgment, it contains potential problems (as mentioned above ). However, the first method also has a defect, that is, the scalability operation is inconvenient. For example, if the program runs only once, it is popped up and displayed to the beginning. The latter method is advantageous.