遍历进程

//下面类使用的是遍历进程,根据进程名判断  
  //参考  
  using   System;  
  using   System.Text.RegularExpressions;  
   
   
  using   System.Diagnostics;  
  using   System.Runtime.InteropServices;    
   
  namespace   HandleRunningProcess  
  {  
  ///   <summary>  
  ///   判断是否已经有实例在运行的类  
  ///   </summary>  
  public   class   CHandleRunningPro  
  {  
  ///   <summary>  
  ///   const   int,   ShowWindowAsync   使用时的参数,让窗体正常显示确保没有隐藏和最小化。  
  ///   </summary>  
  private   const   int   WS_SHOWNORMAL   =   1;    
   
  ///   <summary>  
  ///   功能:遍历所有运行的例程,判断是否已经有相同名字的例程。                
  ///   实现:遍历所有运行的例程,如果有与自己名字相同的比较   ID   是否相同。  
  ///               如果ID不同说明已经有实例在运行,则把该实例返回。  
  ///               如果没有则返回   null  
  ///   </summary>  
  ///   <returns>有相同名字的例程返回其   process,否则返回null</returns>  
  private   Process   GetRunningInstance()  
  {  
  Process   current   =   Process.GetCurrentProcess();  
  Process[]   processes   =   Process.GetProcessesByName   (current.ProcessName);  
   
  //遍历正在有相同名字运行的例程  
  foreach   (Process   process   in   processes)  
  {  
  //忽略现有的例程  
  if   (process.Id   !=   current.Id)  
  {  
  return   process;  
  }  
  }  
   
  //没有其它的例程,返回Null  
  return   null;  
  }  
   
  //接下来调用两个WinAPI,其功能将在包装方法中描述,    
  [DllImport("User32.dll")]    
  private   static   extern   bool   ShowWindowAsync(IntPtr   hWnd,   int   cmdShow);    
  [DllImport("User32.dll")]    
  private   static   extern   bool   SetForegroundWindow(IntPtr   hWnd);    
  //以上的方法声明为私有,对其进一步包装,  
  ///   <summary>  
  ///   功能:HandleRunningInstance静态方法为获取应用程序句柄,设置应用程序为前台运行,并返回bool值。              
  ///   实现:确保窗口没有被最小化或最大化。  
  ///               设置为前台显示。  
  ///   </summary>  
  ///   <param   name="instance">准备设置成前台运行的程序</param>  
  ///   <returns></returns>  
  private   bool   HandleRunningInstance(Process   instance)    
  {    
  //确保窗口没有被最小化或最大化    
  ShowWindowAsync(instance.MainWindowHandle,   WS_SHOWNORMAL);    
  //设置为foreground   window    
  return   SetForegroundWindow(instance.MainWindowHandle);    
  }    
   
  ///   <summary>  
  ///   功能:查找相同名字的进程,有则前台显示,无则返回   false  
  ///   实现:1   查找相同名字的进程。  
  ///               2   有相同名字的进程,将其前台显示,返回   true  
  ///               3   无相同名字,返回   false  
  ///   </summary>  
  ///   <returns>有相同名字   true,   无相同名字   false</returns>  
  public   bool   HandleRunningInstance()    
  {    
  Process   p   =   GetRunningInstance();    
  if   (p   !=   null)    
  {    
  HandleRunningInstance(p);    
  return   true;    
  }    
  return   false;    
  }    
  }  
  }  
posted @ 2008-05-09 21:39  绥山潇洒哥  阅读(716)  评论(0编辑  收藏  举报