让Window程序只能运行一个实例
2009年05月27日
by junstyle
210 views
0 comments
如何让window运用程序只有一个实例,重复运行即会显示以前打开的实例。
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
namespace Junstyle
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
if( Exist() )
{
Application.Exit();
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new frmMain() );
}
[DllImport( "User32.dll" )]
private static extern bool ShowWindowAsync( System.IntPtr hWnd, int cmdShow );
[DllImport( "User32.dll" )]
private static extern bool SetForegroundWindow( System.IntPtr hWnd );
public static bool Exist()
{
bool ret = false;
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName( current.ProcessName );
//遍历与当前进程名称相同的进程列表
foreach( Process process in processes )
{
//Ignore the current process
if( process.Id != current.Id )
{
if( Assembly.GetExecutingAssembly().Location.Replace( "/", "\\" ) == current.MainModule.FileName )
{
ShowWindowAsync( process.MainWindowHandle, 1 ); //调用api函数,正常显示窗口
SetForegroundWindow( process.MainWindowHandle ); //将窗口放置最前端。
return true;
}
}
}
return ret;
}
}
}