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();
}本文出自 “花开花落” 博客,谢绝转载!
原文:http://020618.blog.51cto.com/6098149/1654763