当前位置:编程学习 > C#/ASP.NET >>

确保只有一个程序实例运行(C#)之解决方案

答案:转帖自http://www.yesky.com/20030407/1661941.shtml

如何确保在C#中只有一个程序(实例)运行?

  解答:主要应用System.Diagnostics名字空间中的Process类来实现,思路,我们在运行程序前,查找进程中是否有同名的进程,同时运行位置也相同程,如是没有运行该程序,如果有,就将同名的同位置的程序窗口置前.
主要代码:


[C#]
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//查找相同名称的进程
foreach (Process process in processes)
{
//忽略当前进程
if (process.Id != current.Id)
{
//确认相同进程的程序运行位置是否一样.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;

上一个:俺写的一个简单的字符串处理函数(可能会有用)
下一个:在C#中调用VB.NET函数实例

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,