方法1:
public static void Main(string[] args)
{
//声明互斥体
System.Threading.Mutex mutex = new System.Threading.Mutex(false, "ThisShouldOnlyRunOnce");
//判断互斥体是否使用中
bool Running = !mutex.WaitOne(0, false);
if (! Running)
Application.Run(new FormMain());
else
MessageBox.Show("应用程序已经启动!");
}
方法2:
//添加引用
using System.Runtime.InteropServices;
//申明
[StructLayout( LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public int lpSecurityDescriptor;
public int bInheritHandle;
}
[System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int GetLastError(); [System.Runtime.InteropServices.DllImport("kernel32")]
private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes,bool bInitialOwner,string lpName); [System.Runtime.InteropServices.DllImport("kernel32")]
private static extern int ReleaseMutex(IntPtr hMutex);
const int ERROR_ALREADY_EXISTS = 0183;
//得到正在运行的例程
Process instance = RunningInstance();
if (instance == null)
{
//如果没有其它例程,就新建一个窗体
Application.Run(new Form1());
}
else
{
//处理发现的例程
//HandleRunningInstance(instance);
Application.Exit();//退出
}
}
//得到正在运行的例程
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//遍历正在有相同名字运行的例程
foreach (Process process in processes)
{
//忽略现有的例程
if (process.Id != current.Id)
{
//确保例程从EXE文件运行
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") ==
current.MainModule.FileName)
{
//返回另一个例程实例
return process;
}
}
}