JudgmentProgramWhether the program is running or not. There are many methods to run only one instance. The following two methods are recorded,
Method 1: thread mutex
Static Class Program
{
Private Static System. Threading. mutex;
/// <Summary>
/// The main entry point of the application.
/// </Summary>
[Stathread]
Static Void Main ()
{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault ( False );
Mutex = New System. Threading. mutex ( True , " Onlyrun " );
If (Mutex. waitone (0 , False ))
{
Application. Run ( New Mainform ());
}
Else
{
MessageBox. Show ( " The program is running! " , " Prompt " , Messageboxbuttons. OK, messageboxicon. information );
Application. Exit ();
}
}
}
Method 2:
This method of detecting the process name is not absolutely effective. Because after opening the first instance, you can still run the second instance after renaming the running file.
Static Class Program
{
/// <Summary>
/// The main entry point of the application.
/// </Summary>
[Stathread]
Static Void Main ()
{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault ( False );
// Get the name of our process
String P = system. Diagnostics. process. getcurrentprocess (). processname;
// Get the list of all processes by that name
System. Diagnostics. Process [] processes = system. Diagnostics. process. getprocessesbyname (P );
// If there is more than one process
If (Processes. length> 1 )
{
MessageBox. Show ( " The program is running. " , " System prompt " , Messageboxbuttons. OK, messageboxicon. information );
Application. Exit ();
}
Else
{
Application. Run ( New Mainform ());
}
}
}