A few ways to solve a C # program that allows only one instance to run

Source: Internet
Author: User

Method One:
Use thread mutex variables. Determine whether an instance has been run by defining a mutex variable.
Change the main () function in the Program.cs file to the following code:

usingSystem;usingSystem.Windows.Forms;usingSystem.Runtime.InteropServices;namespacenettools{Static classProgram {[DllImport ("user32.dll")]        Private Static extern BOOLFlashWindow (IntPtr hWnd,BOOLBinvert); [DllImport ("user32.dll")]        Private Static extern BOOLFlashWindowEx (intPfwi); /// <summary>        ///The main entry point for the application. /// </summary>[STAThread]Static voidMain () {BOOLRunone; System.Threading.Mutex Run=NewSystem.Threading.Mutex (true,"single_test", outrunone); if(Runone) {run.                ReleaseMutex ();                Application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Frmremote frm=NewFrmremote (); intHDC = frm. Handle.toint32 ();//Write to ...Application.Run (frm); IntPtr a=NewINTPTR (HDC); }            Else{MessageBox.Show ("An instance has been run. "); //IntPtr hdc = new IntPtr (1312810);//read from ...//bool Flash = FlashWindow (hdc, true);            }        }    }}

Description: In the program through the statement System.Threading.Mutex run = new System.Threading.Mutex (True, "single_test", out Runone), to create a mutex variable run, where " Single_test "is the mutex name, and when this method returns, the Boolean value Runone is true if a local mutex or a specified named system mutex is created, or False if the specified naming system mutex already exists. The named mutex is system-wide.
method Two: in the way of judging the process, we before running the program, find out whether the process has the same name process, while the running location is the same process, if the program is not running, 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 StaticSystem.Diagnostics.Process runninginstance () {System.Diagnostics.Process current=System.Diagnostics.Process.GetCurrentProcess (); System.diagnostics.process[] Processes=System.Diagnostics.Process.GetProcesses ();foreach(System.Diagnostics.Process ProcessinchProcesses//find a process with the same name{ if(Process. Id! = Current. ID)//Ignore Current process{//Verify that the same process is running at the same location as the program.if(System.Reflection.Assembly.GetExecutingAssembly (). Location.replace ("/",@"/") ==Current . Mainmodule.filename) {//Return The other process instance.   returnprocess; } } } //No Other instance is 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 run.   );}}  

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 A in the Global atomic table When exiting the program, remember to release the specific atom a oh, or it will not be released until the shutdown. C # is implemented as follows:
1. Affirm the WINAPI function interface

[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]  Public Static externUInt32 Globaladdatom (String lpstring);//adding atoms[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]  Public Static externUInt32 Globalfindatom (String lpstring);//Find Atoms[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]  Public Static externUInt32 Globaldeleteatom (UInt32 natom);//Delete Atom

2. Modify the main () function as follows:

Static voidMain () {if(Globalfindatom ("jiaao_test") ==77856768)//no Atom "jiaao_test" found .{Globaladdatom ("jiaao_test");//add Atomic "Jiaao_test"Application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Application.Run (NewForm1 ()); } Else{MessageBox.Show ("An instance has been run. "); } } 

3. Add the following code to the FormClosed event:
Globaldeleteatom (Globalfindatom ("jiaao_test"));//delete Atom "Jiaao_test"
--------------------------------------*-------*--------*-----------------------------------------------
The above is the basic common idea of creating mutex, personally, the first method is the simplest.

A few ways to solve a C # program that allows 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.