最近在做winform的程序中,需要只能打开一个程序,如果已经存在,则激活该程序的窗口,并显示在最前端。在网上google了一哈,找到了很多的解决方案。这里我整理了3种方案,并经过了测试,现和朋友们分享:
一、使用用互斥量(System.Threading.Mutex)
同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。
bool createNew;
using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
{
if (createNew)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("应用程序已经在运行中...")
using (System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out createNew))
{
if (createNew)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("应用程序已经在运行中...")
System.Threading.Thread.Sleep(1000);
System.Environment.Exit(1);
}
}
System.Environment.Exit(1);
}
}
二、使用进程名
Thread.Sleep(1000);
System.Environment.Exit(1);
}
else
{
Application.Run(new Form1());
}
System.Environment.Exit(1);
}
else
{
Application.Run(new Form1());
}
三、调用Win32 API,并激活并程序的窗口,显示在最前端
private static extern bool SetForegroundWindow(IntPtr hWnd);
{
return process;
}
}
}
return null;
}
return process;
}
}
}
return null;
}
Process process = RuningInstance();
if (process == null)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("应用程序已经在运行中。。。");
if (process == null)
{
Application.Run(new Form1());
}
else
{
MessageBox.Show("应用程序已经在运行中。。。");
HandleRunningInstance(process);
//System.Threading.Thread.Sleep(1000);
//System.Environment.Exit(1);
}
//System.Threading.Thread.Sleep(1000);
//System.Environment.Exit(1);
}