static void Main()
{
bool createdNew;
Mutex mutex = new Mutex(false, "Single", out createdNew);
if (!createdNew)
{
Process currentProcess = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if ((process.Id != currentProcess.Id) &&
(Assembly.GetExecutingAssembly().Location == process.MainModule.FileName))
{
IntPtr mainFormHandle = process.MainWindowHandle;
if (mainFormHandle != IntPtr.Zero)
{
ShowWindowAsync(mainFormHandle, 1);
SetForegroundWindow(mainFormHandle);
}
}
}
//MessageBox.Show("进程已经开启");
return;
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainFrame());
//mutex.ReleaseMutex(); //释放Mutex一次
}
}
我这样写,在关闭窗体的时候释放那里会报错:
mutex.ReleaseMutex()
需要对应 mutex.WaitOne()
,没有 WaitOne 直接 ReleaseMutex 就会报错
Object synchronization method was called from an unsynchronized block of code