winform程序只能打开一个进程

在winform开发中,经常需要限制一个程序只能打开一个进程,以达到项目中的一些特殊要求,所使用的方法也有很多,我这里使用的是Mutex这个进程锁;当程序已经打开的时候,有的时候有需要把焦点设置到已经打开的那个程序的窗体上,这个时候可以时候FindWindow和SetForegroundWindow这两个win32方法,下面来看下代码。

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Windows.Forms;
 5 using System.Runtime.InteropServices;
 6 using System.Threading;
 7 
 8 namespace Test
 9 {
10     static class Program
11     {
12 
13         [DllImport("user32.dll")]
14         public static extern IntPtr FindWindow(String classname, String title);
15         [DllImport("user32.dll")]
16         public static extern void SetForegroundWindow(IntPtr hwnd);
17 
18         /// <summary>
19         /// 应用程序的主入口点。
20         /// </summary>
21         [STAThread]
22         static void Main()
23         {
24             Application.EnableVisualStyles();
25             Application.SetCompatibleTextRenderingDefault(false);
26 
27             bool mutexWasCreated;
28             //
29             Mutex mutex = new Mutex(true"Mutex"out mutexWasCreated);
30             if (!mutexWasCreated)
31             {
32                 //每个窗体的title,当运用程序已经打开的时候,用来获取当前最上面的那个窗体
33                 //然后激活这个窗体,并设置焦点
34                 string[] frmTexts ={
35                                          "窗体1的Title",
36                                          "窗体2的Title",
37                                      };
38                 try
39                 {
40                     foreach (string str in frmTexts)
41                     {
42                         IntPtr ptr = FindWindow(null, str);
43                         //不等于0表示找到了窗体
44                         if (ptr.ToString() != "0")
45                         {
46                             SetForegroundWindow(ptr);
47                             break;
48                         }
49                     }
50                 }
51                 catch
52                 {
53                 }
54                 return;
55             }
56             Application.Run(new Form1());
57             //最后要释放,如果程序中调用了Environment.Exit(0)来推出程序的话,那么最后把mutex设置为全局的
58             //在调用Environment.Exit(0)之前就释放一次,否则要等系统自动释放才可以再次打开程序
59             mutex.ReleaseMutex();
60         }
61     }
62 }
原文地址:https://www.cnblogs.com/liubiaocai/p/2109776.html