class MutexExample
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
bool flag=false;
System.Threading.Mutex mutex=new System.Threading.Mutex(true,"MutexExample",out flag);
if(flag) {
Console.Write("Running");
}
else {
Console.Write("Another is Running");
}
Console.ReadLine();
}
二、
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ServerEpos
{
public class DuplexCheck
{
[DllImport("USER32.DLL", CharSet = CharSet.Auto)]
private static extern int ShowWindow(
System.IntPtr hWnd,
int nCmdShow
);
[DllImport("USER32.DLL", CharSet = CharSet.Auto)]
private static extern bool SetForegroundWindow(
System.IntPtr hWnd
);
private static System.Threading.Mutex mutexObject;
private const int SW_NORMAL = 1;
private DuplexCheck() { }
/// <summary>
/// 已经打开的线程判断
/// </summary>
public static bool IsOpenMutex()
{
OperatingSystem os = Environment.OSVersion;
string appName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
// 你可以开始不同类型的产品,在相同的程序。
//appName = appName + "_" + Emico.Common.Gadget.ProductInfo.GetProductType();
//if ((os.Platform == PlatformID.Win32NT) && (os.Version.Major >= 5))
//{
// // 在Win2000或者以后
// // 不是一台机器,和桌面独家控制。
// appName = @"Local\" + appName;
// //appName = @"Global\" + appName;
//}
try
{
// 生成一个互斥
mutexObject = new System.Threading.Mutex(false, appName);
}
catch (System.ApplicationException)
{
// 多推出全球互斥
ShowPrevProcess();
return true;
}
if (mutexObject.WaitOne(0, false) == false)
{
// 当你不能得到一个互斥
// 多重启动
mutexObject.Close();
ShowPrevProcess();
return true;
}
return false;
}
/// <summary>
/// 释放互斥。
/// </summary>
public static void ReleaseMutex()
{
mutexObject.ReleaseMutex();
mutexObject.Close();
}
/// <summary>具有相同名称运行的进程,以激活主窗口。</summary>
/// <returns>如果已经运行如此。否则,假的。</returns>
public static bool ShowPrevProcess()
{
Process hThisProcess = Process.GetCurrentProcess();
Process[] hProcesses = Process.GetProcessesByName(hThisProcess.ProcessName);
int iThisProcessId = hThisProcess.Id;
foreach (Process hProcess in hProcesses)
{
if (hProcess.Id != iThisProcessId)
{
ShowWindow(hProcess.MainWindowHandle, SW_NORMAL);
SetForegroundWindow(hProcess.MainWindowHandle);
return true;
}
}
return false;
}
}
}