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;
}
}
}
使應用程序只能運行單個實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.