C# WinForm 判斷程序是否已經在運行,且只允許運行一個實例


static class Program
{
   /// <summary>
   /// 應用程序的主入口點。
   /// </summary>
   [STAThread]
   static void Main()
   {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault( false );
 
     //1.這里判定是否已經有實例在運行
     //只運行一個實例
     Process instance = RunningInstance();
     if (instance == null )
     {
       //1.1 沒有實例在運行
       Application.Run( new frmMain());
     }
     else
     {
       //1.2 已經有一個實例在運行
       HandleRunningInstance(instance);
     }
 
     //Application.Run(new frmMain());
   }
 
   //2.在進程中查找是否已經有實例在運行
   #region 確保程序只運行一個實例
   private static Process RunningInstance()
   {
     Process current = Process.GetCurrentProcess();
     Process[] processes = Process.GetProcessesByName(current.ProcessName);
     //遍歷與當前進程名稱相同的進程列表
     foreach (Process process in processes)
     {
       //如果實例已經存在則忽略當前進程
       if (process.Id != current.Id)
       {
         //保證要打開的進程同已經存在的進程來自同一文件路徑
         if (Assembly.GetExecutingAssembly().Location.Replace( "/" , "\\" ) == current.MainModule.FileName)
         {
           //返回已經存在的進程
           return process;
         }
       }
     }
     return null ;
   }
   //3.已經有了就把它激活,並將其窗口放置最前端
   private static void HandleRunningInstance(Process instance)
   {
     ShowWindowAsync(instance.MainWindowHandle, 1); //調用api函數,正常顯示窗口
     SetForegroundWindow(instance.MainWindowHandle); //將窗口放置最前端
   }
   [DllImport( "User32.dll" )]
   private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
   [DllImport( "User32.dll" )]
   private static extern bool SetForegroundWindow(System.IntPtr hWnd);
   #endregion
}
 
 
轉載 http://www.jb51.net/article/82124.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM