首页 > Windows开发 > 详细

[C#]只能运行程序的一个实例

时间:2015-05-25 06:17:27      阅读:250      评论:0      收藏:0      [点我收藏+]

C#实现只能运行程序的一个实例(添加在窗体的Load事件中)

1. 根据进行名限制只能运行程序的一个实例

System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcessesByName(process.ProcessName); 
if ( processList.Length != 1 )
{
    System.Windows.Forms.MessageBox.Show("This computer already have one program running.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    Application.Exit(); 
    return; 
}

2. 根据进行名限制只能运行一个实例的另外一种写法

string modelName = Process.GetCurrentProcess().MainModule.ModuleName; 
string processName = System.IO.Path.GetFileNameWithoutExtension(modelName); 
Process[] processes = Process.GetProcessesByName(processName);//根据进程名创建进程资源数组     
if ( processes.Length > 1 )   
{       
    MessageBox.Show("该程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
    this.Close();   
}

3. 使用互斥量Mutex实现只能运行程序的一个实例

bool exit;       
System.Threading.Mutex newMutex = new System.Threading.Mutex(true, "仅一次", out exit);       
if ( exit )       
{           
    newMutex.ReleaseMutex();//释放互斥量,可以运行新窗体       
}       
else      
{           
    MessageBox.Show("本程序已经有一个实例在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);    
    this.Close();      
}


本文出自 “花开花落” 博客,谢绝转载!

[C#]只能运行程序的一个实例

原文:http://020618.blog.51cto.com/6098149/1654763

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!