2016-06-13 155 views
-1

我试图从Windows控制台应用程序获得的Chrome浏览器窗口的尺寸,我似乎有从Win32 API得到它的问题。试图从Windows API获取Chrome应用程序窗口的高度和宽度?

这是我到目前为止已经完成:

BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam) 
{ 
    DWORD lpdwProcessId; 
    GetWindowThreadProcessId(hwnd,&lpdwProcessId); 
    if(lpdwProcessId==lParam) 
    { 
     g_HWND=hwnd; 
     return FALSE; 
    } 
    return TRUE; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    charArray = "chrome.exe"; 

    // getting process id from name 
    PROCESSENTRY32 entry; 
    entry.dwSize = sizeof(PROCESSENTRY32); 
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); 

    if (Process32First(snapshot, &entry) == TRUE) 
    { 
     while (Process32Next(snapshot, &entry) == TRUE) 
     { 
      CString strProcessName = entry.szExeFile; 

      //if (stricmp(entry.szExeFile, charArray) == 0) 
      if (strProcessName == charArray) 
      { 
       HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); 
       EnumWindows(EnumWindowsProcMy, entry.th32ProcessID); 
       // g_HWND now has HWND for the process chrome.exe. 
       hWindowFromProcess = g_HWND; 
       int result = 0, result2 = 0; 
       result = GetWindowRect(g_HWND, &g_Rect); 

       LONG nWidth = g_Rect.right - g_Rect.left; 
       LONG nHeight = g_Rect.bottom - g_Rect.top; 
       CloseHandle(hProcess); 
      } 
     } 
    } 
} 

当我从RECT结构的结果,我不断收到是遥远的值。例如,当我在1920 x 1080的屏幕上完全最大化窗口时,我获得了71像素的宽度和16像素的高度。我也注意到无论大小如何改变窗口,RECT的值都保持不变。如果我测试另一个窗口(如cmd.exe),我得到正确的RECT值。

所以我假定浏览器的渲染是由比WinAPI的其他的方法来完成。我见过一些关于使用javascript获取浏览器维度的文章,但我需要从Windows应用程序获取这些信息。

+0

你的方法有两个错误。首先,'EnumWindows'枚举系统中的所有顶层窗口。 Chrome可能会使用很多窗口,因此只需选取第一个窗口就不足以知道它是您想要的窗口。其次,当Chrome运行时,你有没有看过任务管理器?它创建了大约4000个不同的流程。所以你不仅可能找到错误的窗口,你很可能从错误的过程中找到错误的窗口。 –

+0

喜乔纳森, 我认为Process32Next()不经过所有的浏览器进程。我在浏览器上检查了Chrome任务管理器(shift-esc),并且我在浏览器任务管理器中报告了while循环中的迭代次数。 (即在关闭所有扩展功能时,每个额外的选项卡会有2个进程+1个)。另外,我还统计了Chrome运行时以及关闭时的运行进程数,并且这些数字持续下降。 –

+1

显然你没有得到正确的窗口。使用Spy ++找到正确的。 –

回答

0

Chrome使用了几个隐形的窗口,你应该跳过这些。 Chrome窗口有自己的类名"Chrome_WidgetWin_1",它可以用来查找窗口(你可以从Spy ++工具找到这个信息)

也试图避免T宏和全局变量。这里是一个Unicode的例子:

int wmain() 
{ 
    HWND hwnd = NULL; 
    for (;;) 
    { 
     hwnd = FindWindowEx(0, hwnd, L"Chrome_WidgetWin_1", 0); 
     if (!hwnd) 
      break; 

     if (!IsWindowVisible(hwnd)) 
      continue;      

     RECT rect; 
     GetWindowRect(hwnd, &rect); 
     int w = rect.right - rect.left; 
     int h = rect.bottom - rect.top; 
     cout << w << ", " << h << "\n"; 
     break; 
    } 

    return 0; 
}