C WinForm Judge whether the program is already running and only one instance is allowed to run with source code
- 2021-09-16 07:48:58
- OfStack
When we develop WinFrom program, we often hope that only one instance of the program is running, so as to avoid running multiple identical programs. 1 is meaningless and 2 is error-prone.
In order to be more convenient to use, the author sorted out a piece of code for his own use, which can judge whether the program is running, only one instance is running, and when the program is running, double-click the program icon and call out the running program directly.
Look at the code below, just add the following code in the entry file of the program:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//1. It is determined here whether an instance is already running
// Run only 1 Instances
Process instance = RunningInstance();
if (instance == null)
{
//1.1 There are no instances running
Application.Run(new frmMain());
}
else
{
//1.2 There are already 1 Instances are running
HandleRunningInstance(instance);
}
//Application.Run(new frmMain());
}
//2. Find out whether an instance is already running in the process
#region Ensure that the program only runs 1 Instances
private static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(current.ProcessName);
// Traverse the list of processes with the same name as the current process
foreach (Process process in processes)
{
// Ignore the current process if the instance already exists
if (process.Id != current.Id)
{
// Ensure that the process to be opened comes from the same process as the existing process 1 File path
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
// Returns an existing process
return process;
}
}
}
return null;
}
//3. If you already have it, activate it and place its window at the front
private static void HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, 1); // Call api Function to display the window normally
SetForegroundWindow(instance.MainWindowHandle); // Place the window at the front
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(System.IntPtr hWnd);
#endregion
}