现在的位置: 首页 > 综合 > 正文

怎样才能获得同一程序全部实例顶级窗口句柄

2013年01月06日 ⁄ 综合 ⁄ 共 2140字 ⁄ 字号 评论关闭

当一个含有窗口的程序只有一个运行实例的时候,可以用FindWindow函数或CWnd::FindWindow函数得到其顶级窗口句柄。
但是当这个程序有多个运行实例同时运行时,FindWindow只能返回最后一个被激活的窗口句柄。
怎样才能得到所有的运行实例呢(这样才可以像所有的实例发送消息么:)).这就要用到EnumWindows函数了。
------------------------------------

EnumWindows

函数功能描述:Enum顶层窗口

1.函数原形
       BOOL EnumWindows(WNDENUMPROC lpEnumFunc,LPARAM lParam);
       //某些时候调用需要采用如下强制转化:EnumWindows((FARPROC)EnumWindowsProc, 0);
2.参数
       WNDENUMPROC lpEnumFunc:回调函数,返回值为TRUE,则继续查找;为FALSE则终止EnumWindows
       LPARAM lParam              :用户定义的数据
3.返回值
       成功返回TRUE,否则返回FALSE
4.适用平台
        Windows NT/2000/XP/95/98/Me
        头文件:Winuser.h
        库文件:User32.lib.
5.例子
        下面代码获取所有窗口的句柄,并保存到向量里
        std::vector<HWND> g_AllWindow;
        BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam)
       {         return g_AllWindow.push_back(hwnd),TRUE;       } //Enum所有窗口,所以总返回TRUE

       void GetAllWindow()
       {
          EnumWindows(&EnumWindowProc,0);
       }
  
       而这个例子可以将你所需的窗口(窗口类为CMainFrame,窗口标题包含MyWindowText)都存储起来
       typedef struct WndCharacter
       {
          char classname[128];
          char wndText[128];
       }WNDChara;
       static bool IsFindWindow(HWND hwnd, LPARAM lParam)        //如果是类函数,需要写成静态函数。
       {   
               char        buf[128];   
               GetClassName(hwnd, buf, sizeof(buf));   
               if(memcmp(buf,((WNDChara *)lParam)->classname,10) != 0)        return false;   
               GetWindowText(hwnd, buf, sizeof(buf));   
               return strstr(buf,((WNDChara *)lParam)->wndText) ? true:false;   
       }   
       std::vector<HWND> g_AllWindow;
       BOOL CALLBACK EnumWindowsProc(HWND hwnd,LPARAM lParam) //注意:类型是BOOL或INT,不是bool
       {  
          if(IsFindWindow(hwnd, lParam))
          {
             g_AllWindow.push_back(hwnd);
          
          }
          return 1;  //要一直return 1.因为需要遍历所有的窗口,一旦返回0将停止遍历。
       }
  
       void GetAllWindow()
       {
          WNDChara wc;
          strncpy(wc.classname, "CMainFrame", 10);
          strncpy(wc.wndText, "MyWindowText", 12);
          EnumWindows(&EnumWindowProc, &wc);
       }
  
======================================
附带:要找所有子窗口,用EnumChildWindows() 函数。
在MFC程序中,调用这些函数可能需要使用全局命名空间
例如
::GetWindowText(hwnd, (LPTSTR)buf, 128);
::GetWindowTextLength(hwnd);
::EnumWindows(&EnumWindowsProc, (long)szAppName))

抱歉!评论已关闭.