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;
}
}
}
使应用程序只能运行单个实例
最新推荐文章于 2021-05-02 12:46:56 发布