方式一: 单进程的实现
View Code
1 static class Program 2 { 3 /// <summary> 4 /// 应用程序的主入口点。 5 /// </summary> 6 [STAThread] 7 static void Main() 8 { 9 Application.EnableVisualStyles(); 10 Application.SetCompatibleTextRenderingDefault(false); 11 12 //获取当前进程名称 13 string currentProcessName = Process.GetCurrentProcess().ProcessName; 14 15 //把该名称的所有进程的列表 16 Process[] process = Process.GetProcessesByName(currentProcessName); 17 18 if (process.Length > 1) 19 { 20 MessageBox.Show("程序已经运行"); 21 return; 22 } 23 Application.Run(new ThMain()); 24 } 25 }
方式二:窗体单例模式的实现
public static Form1 thMian = null;
/// <summary>
/// 获取单个实例
/// </summary>
/// <returns></returns>
public static Form1 GetInstance()
{
if (thMian == null || thMian.IsDisposed == true) //newForm.IsDisposed == true必需,否则会出现“访问已释放资源”的异常
{
thMian = new Form1();
}
else
{
thMian.Activate();
}
return thMian;
}
调用:
GetInstance();
thMian.Show();