Capture all Windows handles (HWND) and process IDs in PHP

Some functions like imagegrabwindow require the HWND (an integer value) to specify which window you want to copy. No problem if you start the process with $x=new COM(...) like in the examples at But how do you get the HWND of windows already opened? I've struggled with com_get_active_object but did not get too far. That's why I've written and compiled a C++ tool for collecting all active HWNDs and process IDs which can be accessed from PHP via the Windows shell. This opens many possibilities. Download GETHWND.ZIP Access via PHP $x=shell_exec("gethwnd.exe"); Output structure: HWND : Window Name : ProcessID; $x will be a string containing the whole list like 0x40492;Perseus #1:472;0x405c2;SysFader:473;...

Code samples

Listhwnd.php Creates a table of all named HWNDs and Process IDs with links for a snapshot. Please note that not all the HWND are actually valid for snapsnots.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <head><title>HWND list</title> <style>td {border:1px solid #333;}</style> </head> <body> <table> <?php $x=shell_exec("gethwnd.exe"); if ($x) { $y=explode(';',$x); foreach ($y as $z) {$a[]=explode(':',$z);} sort($a); foreach($a as $a2) { if (trim($a2[1])>'') {print"\n<tr><td>$a2[0]<td>$a2[1]<td>$a2[2]<td><a href=\"snap.php?hwnd=$a2[0]\">capture</a></tr>";}}} ?> </table></body></html>
snap.php performs the snapshot.
<?php if ($_GET[hwnd]) { $im=imagegrabwindow($_GET[hwnd]); header("Content-type: image/png"); imagepng($im);} else print"hwnd not given"; ?>
gethwnd.php This function returns the HWND if you hand over a window name (in this case the first 10 chars only).
<?php function gethwnd($wintext) { $x=shell_exec("gethwnd.exe"); $a=explode(';',$x); foreach($a as $s) { $a2=explode(':',$s); if (substr($a2[1],0,10)==$wintext) return $a2[0];}} $hwnd=gethwnd("Program Manager"); header("Content-type: image/png"); imagepng($im); ?>
Source in C++:
#include <iostream> #include <windows.h> using namespace std; int main() { HWND h = ::GetTopWindow(0 ); char t[100]; int x; DWORD pid; DWORD dwTheardId; while ( h ) { dwTheardId = ::GetWindowThreadProcessId( h,&pid); x=GetWindowText(h,t,100); cout<<h<<':'<<t<<':'<<pid<<';'; h = ::GetNextWindow( h , GW_HWNDNEXT); }}

Questions? Corrections? Ideas? Comments? main index

This site is based at: