There are many methods to determine whether a program is running so that the program can run only one instance. The following two methods are recorded,
Method 1: thread mutex
Static class Program
{
Private static System. Threading. Mutex mutex;
/// <Summary>
/// 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 already 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>
/// 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 ());
}
}
}
From June's hard work