Use mutex to run a single program instance (C #)

Source: Internet
Author: User

Everyone is developingProgramYou can only run one instance at the same time to implement this function. For VB. net is very easy, as long as you specify a property, but the implementation of C # Is a little tedious.

C # there are also many methods for running a single instance. For example, you can use process to find a process, use API findwindow to find a form, or use mutex atomic operations, among the above methods, it is a good choice to comprehensively consider using mutex.

The following is an example of using mutex to run a single instance:

In C #, find program. CS, where

[Stathread]

Static void main ()

{

//......

}

Is the entry point for running the program. By defaultCodeIt is roughly as follows:

[Stathread]
Static void main ()
{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. Run (New form1 ());
} The code for adding a single instance restriction is as follows:

[stathread]
static void main ()
{< br> bool isapprunning = false;
system. threading. mutex = new system. threading. mutex (
true,
system. diagnostics. process. getcurrentprocess (). processname,
out isapprunning);
If (! Isapprunning)
{< br> MessageBox. Show ("this program is already running. Please do not run it again! ");
environment. exit (1);
}< br> else
{< br> application. enablevisualstyles ();
application. setcompatibletextrenderingdefault (false);
application. run (New form1 ();
}< BR >}

A mutex process (Program), simply put, is to run only one instance of the program in the system. currently, many software have this function. For example, Maxthon can be set to "open only one form" or bitcomet. I also saw this feature of these software to study this problem. to achieve program mutex, there are usually three methods, which are implemented in the C # language below:

Method 1: Use the thread mutex variable. Determine whether the instance is running by defining the mutex variable. C # implementation is as follows:

Change the main () function in the program. CS file to the following code:

Static void main ()
{
Bool runone;
System. Threading. mutex run = new system. Threading. mutex (true, "xinbiao_a_test", out runone );
If (runone)
{
Run. releasemutex ();
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. Run (New form1 ());
}
Else
{
MessageBox. Show ("an instance has been running. ");
}
}

Note: The program uses the statement system. threading. mutex run = new system. threading. mutex (true, "xinbiao_a_test", out runone); to declare a mutex variable Run, where "xinbiao_a_test" is the mutex name, the Boolean runone variable is used to save whether the program has been run.

Implementation Method 2: Determine the process. Before running the program, we can check whether there is a process with the same name in the process. If the process is not running, if yes, it will not run. apply System. the main code is as follows:

1. Add the following functions to the program. CS file:

Public static system. Diagnostics. Process runninginstance ()
{
System. Diagnostics. Process current = system. Diagnostics. process. getcurrentprocess ();
System. Diagnostics. Process [] processes = system. Diagnostics. process. getprocesses ();
Foreach (system. Diagnostics. Process in processes) // query processes with the same name
{
If (process. ID! = Current. ID) // ignore the current process
{// Check whether the running location of the same process is the same.
If (system. reflection. Assembly. getexecutingassembly (). Location. Replace ("/", @ "\") = current. mainmodule. filename)
{// Return the other process instance.
Return process;
}
}
} // No other instance was found, return null.
Return NULL;
}

2. Change the main () function to the following code:

Static void main ()
{
If (runninginstance () = NULL)
{
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. Run (New form1 ());
}
Else
{
MessageBox. Show ("an instance has been running. ");
}
}

Method 3: Perform the global atomic method. Before creating a program, check the global atomic table to see if there is a specific atomic A (added at the time of creation) and stop the creation when the atomic table exists, this indicates that the program has run an instance. If the program does not exist, it will run and want to add a specific atomic A to the global atomic table. Remember to release a specific atomic A when exiting the program, otherwise, the instance will be released after it is shut down. C # implementation:

1. Declare the winapi function interface:

[System. runtime. interopservices. dllimport ("kernel32.dll")]

Public static extern uint32 globaladdatom (string lpstring); // Add an atom

[System. runtime. interopservices. dllimport ("kernel32.dll")]

Public static extern uint32 globalfindatom (string lpstring); // search for Atoms

[System. runtime. interopservices. dllimport ("kernel32.dll")]

Public static extern uint32 uglobaldeleteatom (uint32 natom); // delete an atom

2. Modify the main () function as follows:

Static void main ()
{
If (globalfindatom ("xinbiao_test") = 77856768) // No atom found "xinbiao_test"
{
Globaladdatom ("xinbiao_test"); // Add the atom "xinbiao_test"
Application. enablevisualstyles ();
Application. setcompatibletextrenderingdefault (false );
Application. Run (New form1 ());
}
Else
{
MessageBox. Show ("an instance has been running. ");
}
}

3. Add the following code to the formclosed event:

Globaldeleteatom (globalfindatom ("xinbiao_test"); // Delete the atom "xinbiao_test"

The above is the basic general idea of creating mutex programs (processes). I personally think that the first method is the best. All the above Code has passed the test in vs. net2005.

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.