C # allows only one instance of the solution

Recently doing winform program, you need only open a program, if it already exists, the program's window is activated and displayed in the forefront. Online google a Kazakh, found a lot of solutions. Here I put together three kinds of programs, and tested, and now friends to share:

First, using a mutex (System.Threading.Mutex)

 Synchronization primitives, only granted exclusive access to the shared resource to a thread. When the program starts, it requests a mutex, if we can gain access to the designated exclusive, inaugural run one instance.

Copy the code
Code
 bool createNew;
            using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            {
                if (createNew)
                {
                    Application.Run(new Form1());
                }
                else
                {
                    MessageBox.Show("应用程序已经在运行中...")
                    System.Threading.Thread.Sleep(1000);
                    System.Environment.Exit(1);
                }
            }
Copy the code

 

 

Second, use the process name

 

Copy the code
Code
   Process [] = System.Diagnostics.Process.GetProcessesByName Processes (Application.CompanyName);
            IF (processes.Length>. 1)
            {
                MessageBox.Show ( "application is already running ..");
                the Thread.Sleep (1000);
                System.Environment.Exit (. 1);
            }
            the else
            {
                the Application.Run (new new the Form1 ());
            }
Copy the code

 

 

Third, call the Win32 API, and to activate and program window is displayed in the forefront

 

Copy the code
Code
  /// This function sets the window is generated by the display state of different threads
        /// </ Summary>
        /// <param name = "the hWnd"> window handle </ param>
        /// <param name = "for ncmdshow"> how to specify the window display. See list of allowed values, please refer to the function description section ShowWlndow </ param>
        /// <Returns> visible if the original function, the return value is zero; if the originally hidden function, the return value is zero </ Returns>
        [the DllImport ( "the User32.dll")]
        Private static extern BOOL the ShowWindowAsync (IntPtr the hWnd, for ncmdshow int);
        /// <Summary>
        /// this function creates a thread set the specified window to the foreground, and the window active. Steering the keyboard input window, and for the user to change various visual mark.
        /// foreground window system to create a thread assigned permissions slightly higher than other threads. 
        /// </ Summary>
        /// <param name = "the hWnd"> will be activated and transferred to the handle of the foreground window </ param>
        /// <Returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
Copy the code

 

 

Copy the code
Code
  private const int SW_SHOWNOMAL = 1;
        private static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, SW_SHOWNOMAL);//显示
            SetForegroundWindow(instance.MainWindowHandle);//当到最前端
        }
        private static Process RuningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess();
            Process[] Processes = Process.GetProcessesByName(currentProcess.ProcessName);
            foreach (Process process in Processes)
            {
                if (process.Id != currentProcess.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == currentProcess.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
Copy the code

 

Copy the code
Code
  = RuningInstance Process Process ();
            IF (Process == null)
            {
                the Application.Run (new new the Form1 ());
            }
            the else
            {
                MessageBox.Show ( "application is already running ...");
                HandleRunningInstance(process);
                //System.Threading.Thread.Sleep(1000);
                //System.Environment.Exit(1);
            }
Copy the code

 

Guess you like

Origin www.cnblogs.com/soundcode/p/11357191.html