There are several ways to prevent a program from running multiple instances, such as by using mutexes and process names. And what I want to accomplish is that the first instance is activated when the program runs multiple instances, giving it the focus and displaying it on the front. The main use of two API functions:
- Showwindowasync This function sets the display state of a window generated by a different thread.
- SetForegroundWindow This function sets the thread that creates the specified window to the foreground and activates the window. The keyboard input turns to the window and changes the various visual marks for the user. The system assigns a slightly higher permission to the thread that creates the foreground window than the other threads.
The code is as follows: Reference the following namespaces: |
usingSystem.Runtime.InteropServices;usingSystem.Diagnostics;usingSystem.Reflection;//***************************************************** Static classProgram {/// <summary> ///This function sets the display state of a window generated by a different thread. /// </summary> /// <param name= "HWnd" >window Handle</param> /// <param name= "Cmdshow" >specifies how the window is displayed. To view a list of allowed values, consult the description section of the Showwlndow function. </param> /// <returns>If the function is originally visible, the return value is not 0, and if the function is originally hidden, the return value is zero. </returns>[DllImport ("User32.dll")] Private Static extern BOOLShowwindowasync (IntPtr hWnd,intcmdshow); /// <summary> ///The function creates a thread setting for the specified window to the foreground and activates the window. The keyboard input turns to the window and changes the various visual marks for the user. The system assigns a slightly higher permission to the thread that creates the foreground window than the other threads. /// </summary> /// <param name= "HWnd" >a handle to the window that will be activated and called into the foreground. </param> /// <returns>If the window is set to the foreground, the return value is not 0, and the return value is zero if the window is not set in the foreground. </returns>[DllImport ("User32.dll")] Private Static extern BOOLSetForegroundWindow (IntPtr hWnd); Private Const intWs_shownormal =1; /// <summary> ///The main entry point for the application. /// </summary>[STAThread]Static voidMain () {application.enablevisualstyles (); Application.setcompatibletextrenderingdefault (false); Process instance=runninginstance (); if(Instance = =NULL) {Form1 frm=NewForm1 (); Application.Run (NewForm1 ()); } Else{handlerunninginstance (instance); } } /// <summary> ///Gets the running instance that does not have a running instance that returns null; /// </summary> Public Staticprocess Runninginstance () {Process current=process.getcurrentprocess (); Process[] Processes=Process.getprocessesbyname (current. ProcessName); foreach(Process processinchprocesses) { if(Process. Id! =Current . Id) {if(Assembly.getexecutingassembly (). Location.replace ("/","\\") ==Current . Mainmodule.filename) {returnprocess; } } } return NULL; } /// <summary> ///Displays the programs that have been run. /// </summary> Public Static voidHandlerunninginstance (Process instance) {Showwindowasync (instance. Mainwindowhandle, Ws_shownormal); //displayed, can be commented outSetForegroundWindow (instance. Mainwindowhandle);//put it on the front . } }
Implementation allows a program to open only one instance (other methods)
//===== Create Mutex method: =====BOOLblnisrunning; Mutex Mutexapp=NewMutex (false, assembly.getexecutingassembly (). FullName, outblnisrunning);if(!blnisrunning) {MessageBox.Show ("The program is already running! ","Tips", MessageBoxButtons.OK, messageboxicon.exclamation); return;} //ensure that only one client is running at the same timeSystem.Threading.Mutex mutexmyapplication =NewSystem.Threading.Mutex (false,"OnePorcess.exe");if(!mutexmyapplication.waitone ( -,false) {MessageBox.Show ("program"+ Application.productname +"already running! ", Application.productname, MessageBoxButtons.OK, Messageboxicon.error); return;}//===== Judgment Process method: (can still execute after modifying the program name) =====Process current =process.getcurrentprocess (); Process[] Processes=Process.getprocessesbyname (current. ProcessName);foreach(Process processinchprocesses) { if(Process. Id! =Current . Id) {if(process. Mainmodule.filename==Current . Mainmodule.filename) {MessageBox.Show ("The program is already running! ", Application.productname, MessageBoxButtons.OK, messageboxicon.exclamation); return; } }}
Source: http://www.soaspx.com/dotnet/csharp/csharp_20130319_10168.html
The C # Implementation program starts only once (runs multiple times to activate the first instance, giving it the focus and displaying it at the front end)