首页 > 技术文章 > 控制台——防止程序重复启动

wuqiuxue 2017-10-14 00:30 原文

循环当前所有进程,判断是否存在进程名称一致并且进程Id也一致的情况,如果存在就结束当前进程。

 1 public static Process RunningInstance()
 2 {
 3     Process[] processes = Process.GetProcesses();  //进程列表
 4     Process current = Process.GetCurrentProcess(); //当前进程
 5                                                    //当前进程名称(xxx.vshost.exe或xxx.exe)
 6     string currentName = Path.GetFileName(Assembly.GetCallingAssembly().Location.Replace("/", "\\\\"));
 7     currentName = currentName.Split(new char[] { '.' })[0];//只取主文件名(xxx)
 8     foreach (Process process in processes)
 9     {
10         string procName = process.ProcessName;
11         bool vshost = procName.Contains(".vshost");
12         procName = procName.Split(new char[] { '.' })[0];
13         if (!vshost && string.Compare(procName, currentName, true) == 0 && process.Id != current.Id) return process;
14     }
15     return null;
16 }

程序主函数入口调用方法

1 static void Main(string[] args)
2 {
3     Console.WriteLine("go...");
4     Process proc = RunningInstance();
5     if (proc != null){MessageBox.Show("Please do not repeat start software!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);return;}
6     Console.WriteLine("...");
7     Console.ReadKey();
8 }

 

推荐阅读