您的位置:首页 > 其它

让你的程序只能运行一个实例

2008-05-31 17:06 351 查看
先说一个循环系统进程的方法吧,

//首先取得你的程序当前进程

Process current = Process.GetCurrentProcess();

//用你进程的名字到系统进程中取

Process[] processes = Process.GetProcessesByName(current.ProcessName);

//真的取到了多个就循环他们

foreach (Process process in processes)

{

//因为即使进程名一致但是进程ID仍然会不同,如果在你系统里存在两个你的程序了

if (process.Id != current.Id)

{

if (process.MainModule.FileName

== current.MainModule.FileName)

{

//经过多个判断可以确定你程序的进程在系统中已经有存在了,那么就关掉它吧


MessageBox.Show("程序已经运行!", Application.ProductName,

MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

Application.Exit();

return;

}

}

}

再说另一种使用互斥对象的方法,

//这里第2个参数是保证你程序唯一性的而一个字符串

static Mutex mutex = new Mutex(false, "f880a127-9d21-4907-aa83-6041dc0faa4a");

if (!mutex.WaitOne(1000,false)) //等待1秒, 如果有相同实例运行则给用户提示

{

MessageBox.Show("程序已在运行,如果仍有问题,请检查是否已在系统进程中运行。");

return;

}

try

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new Form1());

}

finally { mutex.ReleaseMutex(); }

总结完毕.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: