When we develop WinFrom programs, we often hope that the program has only one instance to run, so as to avoid running multiple identical programs. One is meaningless and the other is prone to errors.
In order to make it easier to use, the author has sorted out a piece of code that can determine whether the program is running, and only runs one instance, and can realize that when the program is running, double-click the program icon and directly call out the running program.
Let’s look at the code below. Just add the following code to the entry file of the program:
static class Program { /// <summary> /// The main entry point of the application. /// </summary> [STAThread] static void Main() { (); (false); //1. Here we determine whether there is an instance running //Only run one instance Process instance = RunningInstance(); if (instance == null) { //1.1 No instance is running (new frmMain()); } else { //1.2 There is already an instance running HandleRunningInstance(instance); } //(new frmMain()); } //2. Find out whether there is an instance running in the process #region Make sure that the program only runs one instance private static Process RunningInstance() { Process current = (); Process[] processes = (); //Travel over the list of processes with the same name as the current process foreach (Process process in processes) { //If the instance already exists, ignore the current process if ( != ) { // Ensure that the process to be opened comes from the same file path as the existing process if (().("/", "\\") == ) { //Return the existing process return process; } } } return null; } //3. Activate it as it already exists and place its window at the front end private static void HandleRunningInstance(Process instance) { ShowWindowAsync(, 1); //Calling the API function, displaying the window normally SetForegroundWindow(); //Place the window at the front end } [DllImport("")] private static extern bool ShowWindowAsync( hWnd, int cmdShow); [DllImport("")] private static extern bool SetForegroundWindow( hWnd); #endregion }