// Program.cs
using System;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
namespace WindowsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
// 尝试创建一个命名事件
bool createNew;
ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, "MyStartEvent", out createNew);
// 如果该命名事件已经存在(存在有前一个运行实例),则
if (!createNew)
{
// 先写一些数据到注册表中,以便传递给前一个运行实例
Registry.SetValue(@"HKEY_CURRENT_USER\Software\MyMy", "", DateTime.Now.ToLongTimeString());
// 发事件通知
ProgramStarted.Set();
// 等一小会以便前一个运行实例接到通知后恢复显示(也可以采用等待事件通知的方式)
Thread.Sleep(200);
// 将焦点转移到前一个实例
foreach (Process p in Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName))
{
if (p.MainWindowHandle != IntPtr.Zero)
{
SetForegroundWindow(p.MainWindowHandle);
}
}
// 就此退出第二个进程
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static EventWaitHandle ProgramStarted;
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
}
}
方法二:
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.Threading.Mutex mutex = new System.Threading.Mutex(false, "SINGLE_INSTANCE_MUTEX");
if (!mutex.WaitOne(0, false)) //请求互斥体的所属权
{
mutex.Close();
mutex = null;
}
if (mutex != null)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("程序已运行!");
}
}