第一种方法:抓取程序的进程名,在系统已运行进程中检索该进程名是否已经存在
//获取欲启动进程名
string strProcessName = Process.GetCurrentProcess().ProcessName;
//检查进程是否已经启动,已经启动则显示报错信息退出程序。
if (Process.GetProcessesByName(strProcessName).Length > 1)
{
MessageBox.Show("程序不能运行2次!", "系统错误", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, (MessageBoxOptions)0);
return;
}
第二种方法:利用互斥函数
//方案一
Mutex mt = new Mutex(false,"ProcessName");
if (!mt.WaitOne(5))
{
MessageBox.Show("程序不能运行2次!", "系统错误", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK, (MessageBoxOptions)0);
return;
}
//方案二 WPF
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace GXYLaundry_SoftUpdate
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private static Mutex mutex;
public App()
{
this.Startup += new StartupEventHandler(App_Startup);
}
private void App_Startup(object sender, StartupEventArgs e)
{
bool ret;
mutex = new Mutex(true, "MyApp", out ret);
if (!ret)
{
Environment.Exit(0);
}
}
}
}