C # WINFORM: judge whether the program is running and only one instance can be run

Source: Internet
Author: User

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
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.