C# 调用API枚举窗体,根据标题还原窗体
作者:C/S框架网  发布日期:2013-07-20 20:21:51
  C# 调用API枚举窗体,根据标题还原窗体




贴图图片


C# Code:

public partial class Form1 : Form
{
   public const int SW_RESTORE = 9; //与 SW_SHOWNORMAL 1 相同
   public const int SW_SHOWMAXIMIZED = 3;
   
   [DllImport("user32", SetLastError = true)]
   public static extern int GetWindowText(
   IntPtr hWnd,//窗口句柄
   StringBuilder lpString,//标题
   int nMaxCount //最大值
   );
   
   [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
   public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
   
   /// <summary>
   /// 枚举窗体的回调函数
   /// </summary>
   /// <param name="hWnd"></param>
   /// <param name="lParam"></param>
   /// <returns></returns>
   public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
   
   [DllImport("user32")]
   public static extern int EnumWindows(EnumWindowsProc hWnd, IntPtr lParam);
   
   public Form1()
   {
      InitializeComponent();
   }
   
   private void button1_Click(object sender, EventArgs e)
   {
      EnumWindowsProc callBack = new EnumWindowsProc(OpenOldWindow);
      int i = EnumWindows(callBack, IntPtr.Zero);
      
   }
   
   /// <summary>
   /// 枚举窗体的回调函数,还原显示已打开的帮助文档
   /// </summary>
   /// <param name="hWnd"></param>
   /// <param name="lParam"></param>
   /// <returns></returns>
   public bool OpenOldWindow(IntPtr hWnd, IntPtr lParam)
   {
      StringBuilder sb = new StringBuilder(255);
      GetWindowText(hWnd, sb, sb.Capacity);
      
      if (sb.Length > 0)
      {
         //匹配窗体的标题成功,表示帮助文档已经打开,还原窗体
         if (sb.ToString().IndexOf(@txtCaption.Text) >= 0)
         {
            ShowWindow(hWnd, SW_RESTORE);
            ShowWindow(hWnd, SW_SHOWMAXIMIZED);
            return false;
         }
      }
      return true;
   }
   
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇