Go to C # allow only one instance to run

Source: Internet
Author: User

Source: http://blog.csdn.net/jin20000/article/details/3136791

A mutex process (a program), simply put, is that only one instance of the program can run in the system. Many software now have this feature, such as Maxthon can be set to "Allow only one form to open", as well as BitComet and so on.  I also see this feature of the software to study this problem. To implement mutually exclusive programs, there are usually three ways, which are implemented in the C # language:

Implementation method One: Use the thread mutex variable. Determine whether an instance has been run by defining a mutex variable. C # is implemented as follows:

Change the main () function in the Program.cs file to the following code:

        Static voidMain () {BOOLbcreatednew; //Create A new mutex using specific mutex nameMutex m =NewMutex (true,"Myuniquename", outbcreatednew); if(bcreatednew) {//M.releasemutex ();//do not release the mutex, or you can open the second run window when you repeat it for the second time.Application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Application.Run (NewMainPage ()); }            Else{MessageBox.Show ("The program is already running! "); }        }

Description: The program through the statement mutex m = new Mutex (true, "Myuniquename", out bcreatednew), to declare a mutex variable run, where "Myuniquename" is the mutex name, The Boolean variable bcreatednew is used to save whether the program case has already been run.

Implementation method Two: The way of judging the process, we run the program, to find whether the process has the same name of the process, while the running location is the same process, if not run the program, if there is not run. In C # Application of the Process class in the System.Diagnostics namespace, the main code is as follows:

1, add the function in the Program.cs file as follows:

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 process in processes)//Find the process with the same name
{
if (process. Id! = Current. ID)//Ignore current process
{//Verify that the program running the same process is the same location.
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 already been run. ");
}
}

Implementation method Three: Global atomic method, before you create a program, check the Global atomic table to see if there is a specific atom a (added at the time of creation), the existence of a stop creation, indicating that the program has run an instance, does not exist run the program and want to add a specific atom in the global atomic table A; Remember to release specific atoms a It will not be released until it is shut down. C # is implemented as follows:

1, DECLARE WINAPI function interface:

[System.Runtime.InteropServices.DllImport ("kernel32.dll")]

public static extern UInt32 Globaladdatom (String lpstring); Adding atoms

[System.Runtime.InteropServices.DllImport ("kernel32.dll")]

public static extern UInt32 Globalfindatom (String lpstring); Find atoms

[System.Runtime.InteropServices.DllImport ("kernel32.dll")]

public static extern UInt32 Globaldeleteatom (UInt32 natom); Delete Atom

2. Modify the main () function as follows:

static void Main ()
{
if (Globalfindatom ("xinbiao_test") = = 77856768)//Not found Atom "Xinbiao_test"
{
Globaladdatom ("Xinbiao_test"); Add Atomic "Xinbiao_test"
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Form1 ());
}
Else
{
MessageBox.Show ("an instance has already been run. ");
}
}


3. Add the following code to the FormClosed event:

Globaldeleteatom (Globalfindatom ("xinbiao_test"));//delete Atom "Xinbiao_test"

The above is the basic general idea of creating a mutex (process), and personally, the first method is best. All of the above code is tested in vs.net2005.

Go to C # allow only one instance to run

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.