C#程序防多开又一法
实现思路:
在Main()方法开始时遍历所有进程,获取每个进程的程序集GUID和PID,若发现有跟自己GUID相同且PID不同的进程,就勒令自身退出。
注:
1、采用GUID是为了尽可能保证判定的可靠性,采用进程名太不靠谱。而且程序集GUID是建立项目时就生成的,不随版本、内容的变化而变化,所以除非人为改动,否则同一项目编译若干次都还是那个GUID,用来判断程序集身份再适合不过。题外,网上盛传的互斥体方法,互斥名也建议用GUID;
2、之所以要加上进程ID的判断,是因为遍历的进程中已经包含自身进程,所以必须排除自身;
3、访问某些进程的MainModule属性会引发异常,所以采用try-catch跳过这些进程;
4、经尝试只有C#写的程序才能获取到GUID(有点废话~),但这样已经足够
5、退出自身这里采用的是Environment.Exit()方法,Application.Exit()方法不管用,程序仍然会运行,我猜原因是Application都还没Run过,所以Exit不了~(小弟入门水平,很多东西只能靠坑蒙拐骗~哦不,是连蒙带猜)
6、第一次在cnblogs写博,希望各位前辈多多指教~少扔砖头
1 using System;
2 using System.Diagnostics;
3 using System.Reflection;
4 using System.Runtime.InteropServices;
5 using System.Windows.Forms;
6
7 namespace TestCallAPIRefreshPolicy
8 {
9 static class Program
10 {
11 [STAThread]
12 static void Main()
13 {
14 Guid ownGUID = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(GuidAttribute))).Value);
15 Guid proGUID;
16 int ownPID = Process.GetCurrentProcess().Id;
17 int proPID;
18
19 foreach (Process p in Process.GetProcesses())
20 {
21 try
22 {
23 proGUID = new Guid(((GuidAttribute)Attribute.GetCustomAttribute(Assembly.LoadFile(p.MainModule.FileName), typeof(GuidAttribute))).Value);
24 proPID = p.Id;
25 if (proGUID.Equals(ownGUID) && proPID != ownPID)
26 {
27 MessageBox.Show("程序已运行");
28 Environment.Exit(Environment.ExitCode);
29 }
30 }
31 catch
32 {
33 continue;//遇上进程访问异常就跳过该进程
34 }
35 }
36
37 //若未被Exit,正常启动
38 Application.EnableVisualStyles();
39 Application.SetCompatibleTextRenderingDefault(false);
40 Application.Run(new FmMain());
41 }
42 }
43 }
摘自 ahdung
补充:软件开发 , C# ,