winform程序只能打开一个进程

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

 

ExpandedBlockStart.gif 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/archive/2011/07/18/2109776.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值