Original address: http://www.csharpwin.com/csharpspace/10656r1776.shtml
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 looks like this: reference the following namespaces:
UsingSystem.Runtime.InteropServices;UsingSystem.Diagnostics;UsingSystem.Reflection;//*****************************************************StaticClassprogram {///<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")]PrivateStaticexternBOOL Showwindowasync (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")]PrivateStaticexternboolSetForegroundWindow (IntPtr hWnd);PrivateConstint ws_shownormal =1;///<summary>///The main entry point for the application.///</summary>[STAThread]StaticvoidMain () {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>PublicStaticProcess 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> Show programs that are already running. //</summary> public static void handlerunninginstance (Process instance) { Showwindowasync (instance. Mainwindowhandle, Ws_shownormal); // display, you can comment out SetForegroundWindow (instance. Mainwindowhandle); // put to front end }}
implementation allows a program to open only one instance (other methods)
//===== Create Mutex method: =====boolblnisrunning; Mutex Mutexapp =New Mutex (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 System.Threading.Mutex mutexmyapplication =New System.Threading.Mutex (False"OnePorcess.exe");if (!mutexmyapplication.waitone (100,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 process in processes) { 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;}}}
[Go] allows the program to open only one