使應用程式只能執行單個例項
using System;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Train.OnceInitial
{
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 ) //不僅同名,而且同ID的程序
{
//Make sure that the process is running from the exe file.
if( Assembly.GetExecutingAssembly().Location.Replace( "/", "//" ) == current.MainModule.FileName )
{
ShowWindowAsync( process.MainWindowHandle, 1 ); //呼叫api函式,正常顯示視窗
SetForegroundWindow( process.MainWindowHandle ); //將視窗放置最前端。
return true;
}
}
}
return ret;
}
}
}