using System;
using System.Windows.Forms;//Application
using System.Diagnostics;//Process
using System.Threading;//Mutex
using System.Runtime.InteropServices;//DllImport
using System.IO;//Path
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);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
try
{
bool createdNew;
string appName;
appName = System.Reflection.Assembly.GetExecutingAssembly().Location;
appName = appName.Replace(Path.DirectorySeparatorChar, '_');using (Mutex mutex = new Mutex(true, appName, out createdNew))
{
if (createdNew)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);//将窗口放置最前端
ShowWindowAsync(process.MainWindowHandle, 1); //最小化时放大显示窗口
break;
}
}
}
}
}
catch (Exception ex)
{
}
}
}
同一个目录下,软件只能同时运行一个exe,不同目录,可以再次打开。
原文:https://www.cnblogs.com/chucklu/p/4210432.html