功能编译的时候网上搜索到很多类似文章代码,在这里我整理一下自己用了有效果的代码分享:
方法一:通过程序GUID
#region GUID 程序运行唯一
bool createdNew;
Guid ownGUID = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute))).Value);
//Console.WriteLine(ownGUID.ToString());//
//Console.WriteLine(ownGUID.ToString("N"));//32位数字:
//Console.WriteLine(ownGUID.ToString("D"));//32位数字,用“-”隔开:
//Console.WriteLine(ownGUID.ToString("B"));//32位数字,用连字符隔开,用大括号括起来:
//Console.WriteLine(ownGUID.ToString("P"));//32位数字,用连字符隔开,用括号括起来:
//Console.WriteLine(ownGUID.ToString("X"));//四个用花括号括起来的十六进制值,其中第四个值是八个也用花括号括起来的十六进制值的子集:
Mutex instance = new Mutex(true, ownGUID.ToString("N"), out createdNew);
if (!createdNew)
{
MessageBox.Show("只能运行唯一实例");
Process.GetCurrentProcess().Kill();
}
#endregion
方法二:通过窗体名
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int SendMessage(int hWnd, int msg, int wParam, int lparam);
[System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
[STAThread]
static void Main()
{
//程序运行唯一(多次启动关闭前面程序)
IntPtr hwnd = FindWindow(null, "换成你的窗体名称");
if (hwnd != IntPtr.Zero)
{
SendMessage((int)hwnd, 0x0010, 0, 0);
System.Threading.Thread.Sleep(500);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NetFramework());
}
方法三:通过程序进程名
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
#region 程序唯一
System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
//遍历程序的同名进程组
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName(process.ProcessName))
{
//不是同一进程并且本进程启动时间最晚,则关闭较早进程
if (p.Id != process.Id && (p.StartTime - process.StartTime).TotalMilliseconds <= 0)
{
//关闭最先运行的进程,保留现在运行的进程
p.Kill();//这个地方用kill 而不用Shutdown();的原因是,Shutdown关闭程序在进程管理器里进程的释放有延迟不是马上关闭进程的
//Application.Current.Shutdown();
//return;
//关闭当前运行的进程保留之前的进程
//Process.GetCurrentProcess().Kill();
}
}
#endregion
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new NetFramework());
}
以上是我常用的方法,如果大家有更好的方法欢迎在评论区留言
建议使用第三种方式,前两种狂运行程序会出现多个情况。