方法 1:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
namespace WFForbidAction
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
#region 只允许运行一个实例
Process pr = Process.GetCurrentProcess();
Process[] prlist = Process.GetProcessesByName(pr.ProcessName);
if (prlist.Length >= 2)
{
return;
}
#endregion
Application.Run(new Form1());
}
}
}
方法2:
bool exist;//定义一个bool变量,用来表示是否已经运行
//创建Mutex互斥对象
System.Threading.Mutex newMutex = new System.Threading.Mutex(true, "test", out exist);
if (exist)//如果没有运行
{
newMutex.ReleaseMutex();//运行新窗体
}
else
{
MessageBox.Show("本程序一次只能运行一个实例!",
"温馨提示",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
this.Close();
}