Method 1: If the program is already running, display the running program directly
//Introduce 3 namespaces
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace MyWindow
{
static class Program
{
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Process instance = RunningInstance();
if (instance == null)
{
Form1 frm = new Form1();
Application.Run(new Form1());
}
else
{
HandleRunningInstance(instance);
}
}
/// <summary>
/// Get the running instance, the instance that is not running returns null;
/// </summary>
public static Process RunningInstance()
{ Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); foreach (Process process in processes) { if (process.Id != current.Id) { if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) { return process; } }
}
return null;
}
/// <summary>
/// Display the running programs.
/// </summary>
public static void HandleRunningInstance(Process instance)
{ ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //Display, you can comment out SetForegroundWindow(instance.MainWindowHandle); // Put it on the front end } } }
Method 2: If the program is already running, it only prompts "there is a program running"
System.Threading.Mutex mutex;
bool isNew;
mutex = new System.Threading.Mutex(true, "myproject", out isNew);
if (isNew)
{ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("This program is already running"); }