先说下我详细的几点需求(假设程序名为"A.exe")
1.程序只能同时打开一个实例.
2.在A.exe已经启动的情况下,双击A.exe,则把已经启动的A.exe激活,并呈现到最前.
3.复制A.exe,命名为B.exe,在A.exe已经启动的情况下,双击B.exe,则把A.exe激活,并呈现到最前.
好,现在就来看看网络上的解决方案
1.互斥法
bool createdNew; Mutex instance = new Mutex(true,"互斥名(保证在本机中唯一)", out createdNew); if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); instance.ReleaseMutex(); } else { MessageBox.Show("已经启动了一个程序,请先退出!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } |
评价:
个人认为这种方法非常的好,能做出判断的准确,即使启动复制的执行文件,依然可以提示"已经启动一个程序,请先退出!".这样,它满足了上述需要中的第一条和第三条的前半部分.但是有一个不足:无法激活已经启动的程序(至少我不知道怎么实现 ,如果有谁知道用互斥可以实现以上三个要求,请留言告诉我,不胜感激!)
2.Process法
添加如下函数:
public static Process RunningInstance() { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); //Loop through the running processes in with the same name foreach (Process process in processes) { //Ignore the current process if (process.Id != current.Id) { //Make sure that the process is running from the exe file. if (Assembly.GetExecutingAssembly().Location.Replace("/", "\") == current.MainModule.FileName) { //Return the other process instance. return process; } } } //No other instance was found, return null. return null; } |