Re: How do you obtain a Window Handle?
"Check Abdoul" <check abdoul at mvps dot org> wrote:
Take a look at the CWnd::GetWindow() member function. You should be able to
pass GW_CHILD and then GW_NEXT in a loop to get all the child windows of a
given main window. If you want to do it without MFC, then use the
GetWindow() API. Something like
TCHAR sClassName[MAX_PATH+1] = {0};
HWND hWndChild = ::GetWindow( hWndParent, GW_CHILD);
while ( hWndChild != NULL )
{
// Do something with the hWndChild. For example call
// GetClassName(hWndChild, sClassName, MAX_PATH );
// to get its window class name
hWndChild = ::GetWindow(hWndChild, GW_HWNDNEXT);
}
I once wrote some code based on that method. It's recursive and
displays all windows in the system in a CTreeCtrl. Just like Spy++.
Since results are sometimes slightly different I'm wondering what's
buggy. Spy++ or my code. I guess Spy++ ;)
Hans
////////// Top of file ////////////////////
void CWindowDlg::PopulateWinTree()
{
CString str;
TVINSERTSTRUCT tvi;
c_winTree.DeleteAllItems();
HWND hwnd = ::GetDesktopWindow();
str = FormatEntry(hwnd);
str += _T("(Desktop)");
tvi.hParent = TVI_ROOT;
tvi.hInsertAfter = TVI_ROOT;
tvi.item.mask = TVIF_PARAM | TVIF_TEXT;
tvi.item.lParam = (LPARAM) hwnd;
tvi.item.pszText = (LPTSTR) LPCTSTR(str);
HTREEITEM hRoot = c_winTree.InsertItem (&tvi);
hwnd = ::GetWindow(::GetDesktopWindow(), GW_CHILD);
RecurseWindows(hwnd, hRoot);
c_winTree.Expand(hRoot, TVE_EXPAND);
}
HTREEITEM CWindowDlg::RecurseWindows(HWND hwnd, HTREEITEM hParent)
{
TVINSERTSTRUCT tvi;
HTREEITEM hTree = 0;
CString str;
if (hwnd == 0)
return 0;
hwnd = ::GetWindow(hwnd, GW_HWNDFIRST);
tvi.hParent = hParent;
tvi.hInsertAfter = TVI_LAST;
tvi.item.mask = TVIF_PARAM | TVIF_TEXT ;
while (hwnd)
{
if (::GetWindowLong(hwnd, GWL_STYLE) & WS_VISIBLE)
{
// Visible Window
}
else
{
// Hidden Window
}
str = FormatEntry(hwnd);
tvi.item.pszText = (LPTSTR) LPCTSTR(str);
tvi.item.lParam = (LPARAM) hwnd;
hTree = c_winTree.InsertItem (&tvi);
c_winTree.SetItem (&tvi.item);
RecurseWindows(::GetWindow(hwnd, GW_CHILD), hTree);
hwnd = ::GetWindow(hwnd, GW_HWNDNEXT);
}
return hTree;
}
CString& CWindowDlg::FormatEntry(HWND hwnd)
{
static CString str;
TCHAR wndtext[256];
TCHAR classname[256];
wndtext[0] = classname[0] = _T('\0');
::GetWindowText(hwnd, wndtext, sizeof(wndtext)/sizeof(TCHAR));
::GetClassName(hwnd, classname,
sizeof(classname)/sizeof(TCHAR));
str.Format (_T("%08Xh \"%s\" \'%s\' "), hwnd, wndtext,
classname);
return str;
}
void CWindowDlg::OnRefresh()
{
PopulateWinTree();
}
////////// Bottom of file ////////////////////