C# Winform程序防止多開的方法總結(親測)


1、Winform啟動的時候,檢測是否存在同樣的進程名,防止程序多開;

 1     static class Program
 2     {
 3         /// <summary>
 4         /// 應用程序的主入口點。
 5         /// </summary>
 6         [STAThread]
 7         static void Main()
 8         {
 9             Process[] processes = Process.GetProcesses();
10             Process currentProcess = Process.GetCurrentProcess();
11             bool processExist = false;
12             foreach (Process p in processes)
13             {
14                 if (p.ProcessName == currentProcess.ProcessName && p.Id != currentProcess.Id)
15                 {
16                     processExist = true;
17                 }
18             }
19 
20             if (processExist)
21             {
22                 Application.Exit();
23             }
24             else
25             {
26                 Application.EnableVisualStyles();
27                 Application.SetCompatibleTextRenderingDefault(false);
28                 Application.Run(new Form1());
29             }
30         }
31     }

 

 1     static class Program
 2     {
 3         /// <summary>
 4         /// 應用程序的主入口點。
 5         /// </summary>
 6         [STAThread]
 7         static void Main()
 8         {
 9             string processName = Process.GetCurrentProcess().ProcessName;
10             Process[] processes = Process.GetProcessesByName(processName);
11             //如果該數組長度大於1,說明多次運行
12             if (processes.Length > 1)
13             {
14                 MessageBox.Show("程序已運行,不能再次打開!");
15                 Environment.Exit(1);
16             }
17             else
18             {
19                 Application.EnableVisualStyles();
20                 Application.SetCompatibleTextRenderingDefault(false);
21                 Application.Run(new Form1());
22             }
23         }
24     }

2、利用Mutex互斥對象防止程序多開;

 1     static class Program
 2     {
 3         /// <summary>
 4         /// 應用程序的主入口點。
 5         /// </summary>
 6         [STAThread]
 7         static void Main()
 8         {
 9             bool isAppRunning = false;
10             Mutex mutex = new Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out isAppRunning);
11             if (!isAppRunning)
12             {
13                 MessageBox.Show("程序已運行,不能再次打開!");
14                 Environment.Exit(1);
15             }
16             Application.EnableVisualStyles();
17             Application.SetCompatibleTextRenderingDefault(false);
18             Application.Run(new Form1());
19         }
20     }

—————————————————————————————————————————————————


免責聲明!

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



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