使应用程序只能运行单个实例

    技术2022-05-11  10

     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;            }        } }


    最新回复(0)